Welcome to Subscribe On Youtube
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: 4 Explanation: The unique elements are [1,3], and the sum is 4.
Example 2:
Input: nums = [1,1,1,1,1] Output: 0 Explanation: There are no unique elements, and the sum is 0.
Example 3:
Input: nums = [1,2,3,4,5] Output: 15 Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
Solutions
-
class Solution { public int sumOfUnique(int[] nums) { int[] cnt = new int[101]; for (int x : nums) { ++cnt[x]; } int ans = 0; for (int x = 0; x < 101; ++x) { if (cnt[x] == 1) { ans += x; } } return ans; } }
-
class Solution { public: int sumOfUnique(vector<int>& nums) { int cnt[101]{}; for (int& x : nums) { ++cnt[x]; } int ans = 0; for (int x = 0; x < 101; ++x) { if (cnt[x] == 1) { ans += x; } } return ans; } };
-
class Solution: def sumOfUnique(self, nums: List[int]) -> int: cnt = Counter(nums) return sum(x for x, v in cnt.items() if v == 1)
-
func sumOfUnique(nums []int) (ans int) { cnt := [101]int{} for _, x := range nums { cnt[x]++ } for x := 0; x < 101; x++ { if cnt[x] == 1 { ans += x } } return }
-
function sumOfUnique(nums: number[]): number { const cnt = new Array(101).fill(0); for (const x of nums) { ++cnt[x]; } let ans = 0; for (let x = 0; x < 101; ++x) { if (cnt[x] == 1) { ans += x; } } return ans; }
-
class Solution { /** * @param Integer[] $nums * @return Integer */ function sumOfUnique($nums) { $sum = 0; for ($i = 0; $i < count($nums); $i++) { $hashtable[$nums[$i]] += 1; if ($hashtable[$nums[$i]] == 1) { $sum += $nums[$i]; } if ($hashtable[$nums[$i]] == 2) { $sum -= $nums[$i]; } } return $sum; } }
-
impl Solution { pub fn sum_of_unique(nums: Vec<i32>) -> i32 { let mut cnt = [0; 101]; for x in nums { cnt[x as usize] += 1; } let mut ans = 0; for x in 1..101 { if cnt[x] == 1 { ans += x; } } ans as i32 } }