LeetCode 954. Two-fold pair array

Original title link

  1. Use the hash table to count the number of times each number appears, divide the positive and negative into consideration, and directly operate on the number of each element in the array.
  2. When 2 times (a negative number is 1/2) the number of elements minus the number of the current value is less than 0, it proves that the current value is redundant and does not match.
  3. It also utilizes the function of map automatic sorting.

The code written by myself is not very good, refer to the solution

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;
    }
};

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/112755900