- 使用hash表统计每个数字出现的次数,分正负考虑二倍情况,直接在数组中每个元素数量上进行操作。
- 当2倍(负数为1/2)元素的数量减去当前值的数量小于0时候,证明当前值会有多余,不匹配。
- 还利用了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;
}
};