leetcode954.二倍数对数组C++(绝对值排序)

leetcode954.二倍数对数组C++(绝对值排序),第1张

链接:

https://leetcode-cn.com/problems/array-of-doubled-pairs/

描述和示例:


代码:
class Solution {
public:
    bool canReorderDoubled(vector<int>& arr) {
        unordered_map<int, int> h;//先用hash统计元素的个数
        for (int x: arr) 
            ++h[x];
        vector<int> v;
        v.reserve(h.size());
        for (auto [x, _]: h) 
            v.push_back(x);
        sort(v.begin(), v.end(), [](int a, int b){return abs(a) < abs(b);});//按照绝对值排序
        for (int x: v)//删除里面的元素
            if (h[x+x] < h[x]) 
                return false;
            else 
                h[x+x] -= h[x];
        return true;
    }
};

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

原文地址: http://outofmemory.cn/langs/563854.html

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

发表评论

登录后才能评论

评论列表(0条)

保存