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.
Solution
We use an unordered_map to save the unique elements in nums. If the number appeared more than once, mark the number to false as “not unique”.
Finally, accumulate the numbers in map to get the results.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int sumOfUnique(vector<int>& nums) {
unordered_map<int, bool> hashMap;
for (auto i: nums) {
if (hashMap.find(i) == hashMap.end())
hashMap[i] = true;
else
hashMap[i] = false;
}
return accumulate(hashMap.begin(), hashMap.end(), 0, [](int sum, const auto& p) {
return sum + (p.second? p.first: 0);
});
}
};