[leetcode] 1748. Sum of Unique Elements

网友投稿 886 2022-08-23

[leetcode] 1748. Sum of Unique elements

[leetcode] 1748. Sum of Unique Elements

Description

You are given an integer array nums. the unique elements of an array are the elements that appear exactly once in the array.

Return the sum of all the unique elements of nums.

Example 1:

Input: nums = [1,2,3,2]Output: 4Explanation: The unique elements are [1,3], and the sum is 4.

Example 2:

Input: nums = [1,1,1,1,1]Output: 0Explanation: There are no unique elements, and the sum is 0.

Example 3:

Input: nums = [1,2,3,4,5]Output: 15Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.

Constraints:

1 <= nums.length <= 1001 <= nums[i] <= 100

分析

题目的意思是:给定数组,求出频率为1的数字的求和。 思路也很直接,用字典统计频率,然后对齐中频率为1的数求和就行了。

代码

class Solution: def sumOfUnique(self, nums: List[int]) -> int: d=defaultdict(int) for num in nums: d[num]+=1 res=0 for k,v in d.items(): if(v==1): res+=k return res

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 89. Gray Code
下一篇:[leetcode] 274. H-Index
相关文章

 发表评论

暂时没有评论,来抢沙发吧~