LeetCode 954. 二倍数对数组

原题链接

  1. 使用hash表统计每个数字出现的次数,分正负考虑二倍情况,直接在数组中每个元素数量上进行操作。
  2. 当2倍(负数为1/2)元素的数量减去当前值的数量小于0时候,证明当前值会有多余,不匹配。
  3. 还利用了map自动排序的功能。

自己写的代码不太好,参考了题解

class Solution {
    
    
public:
    bool canReorderDoubled(vector<int>& A) {
    
    
        map<int, int> cnt;
        int match;

        for(int i: A) cnt[i]++;
        for(auto i = cnt.begin(); i != cnt.end(); ++i)
        {
    
    
            if(i->second > 0)  // 先看数量,等于0 直接pass
            {
    
    
                if(i->first > 0)   // 分正负考虑
                {
    
    
                    match = i->first * 2;
                }
                else
                {
    
    
                    if(i->first % 2) return false;
                    match = i->first / 2;
                }
                cnt[match] -= i->second;   // 这一步很关键
                if(cnt[match] < 0) return false;
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43078427/article/details/112755900