解题思路:
很容易想到两种思路,第一种用Map记录个数,然后遍历Map把数量为1的元素相加,代码如下:
class Solution {
public:
int sumOfUnique(vector& nums) {
unordered_map mp;
for(int& num : nums) {
mp[num] ++;
}
int ans = 0;
for(auto&[a, b] : mp) {
if(b == 1) {
ans += a;
}
}
return ans;
}
};
另一种思路是先加上,然后Map也记录,一旦重复就减去,当然要注意一旦出现三个及以上的情况就不要继续减了,代码如下:
class Solution {
public:
int sumOfUnique(vector& nums) {
unordered_map mp;
int ans = 0;
for(int& num : nums) {
if(mp[num] == 0) {
ans += num;
mp[num] = 1;
} else if(mp[num] == 1){
ans -= num;
mp[num] = 2;
}
}
return ans;
}
};


![LeetCode 1748 唯一元素的和[Map] HERODING的LeetCode之路 LeetCode 1748 唯一元素的和[Map] HERODING的LeetCode之路](http://www.mshxw.com/aiimages/31/720715.png)
