LeetCode 954 二倍数对数组[自定义排序 Map] HERODING的LeetCode之路

LeetCode 954 二倍数对数组[自定义排序 Map] HERODING的LeetCode之路,第1张

解题思路:
常规的数字配对题目,用map记录下来每个数,再根据是否二倍关系判断,如果是,则继续,如果没有二倍数,返回false,代码如下:

bool cmp(const int a, const int b) {
    return abs(a) < abs(b);
}

class Solution {
public:
    bool canReorderDoubled(vector<int>& arr) {
        unordered_map<int, int> mp;
        for(int & a : arr) {
            mp[a] ++;
        }
        if(mp[0] % 2) {
            return false;
        }
        sort(arr.begin(), arr.end(), cmp);
        for(int i = 0; i < arr.size(); i ++) {
            if(mp[arr[i]] == 0) continue;
            if(mp[arr[i]] > 0 && mp[arr[i] * 2] > 0) {
                mp[arr[i]] --;
                mp[arr[i] * 2] --;
            }  else return false;
        }
        return true;
    }
};

虽然但是,上述的 *** 作还是有很多冗余,比如需要对数组进行排序后再遍历判断,其实直接在map中遍历判断更省事,代码如下:

class Solution {
public:
    bool canReorderDoubled(vector<int>& arr) {
        map<int, int> mp;
        for(int & a : arr) {
            mp[a] ++;
        }
        for(auto& [a, b] : mp) {
            if(b < 0) return false;
            if(b == 0) continue;
            if(a > 0) {
                if(!mp.count(a * 2)) return false;
                mp[a * 2] -= b;
            } else {
                if(!mp.count(a / 2) || a % 2 != 0) return false;
                mp[a / 2] -= b;
            }
        }
        return true;
    }
};

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

原文地址: https://outofmemory.cn/langs/564260.html

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

发表评论

登录后才能评论

评论列表(0条)

保存