LeetCode 1748 唯一元素的和[Map] HERODING的LeetCode之路

LeetCode 1748 唯一元素的和[Map] HERODING的LeetCode之路,第1张

LeetCode 1748 唯一元素的和[Map] HERODING的LeetCode之路


解题思路
很容易想到两种思路,第一种用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;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5718539.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存