Medium difficulty 32 Favorites sharing Switch to English to receive dynamic feedback
Given an integer array with an even length , return A
only if the A
"for each 0 <= i < len(A) / 2
has A[2 * i + 1] = 2 * A[2 * i]
" is satisfied after reorganization true
; otherwise, return false
.
Problem solution: classification + map (hash_map should be used, but I don't know why hash_map reports an error in LeetCode)
class Solution {
public:
//只找绝对值比自己小的,8 4 2 16 会true
bool canReorderDoubled(vector<int>& A) {
int n=A.size();
if(!n)
return true;
sort(A.begin(),A.end());
map<int,int>mp;
for(int i : A) mp[i]++;
//map有序
for(int i=0;i<n;i++)
{
int match=-1;
if(mp[A[i]]>0)
{
if(A[i]>0)//正数 从小到大 找*2的
match=A[i]*2;
else//负数和0 绝对值从大到小,找/2的
{
if(A[i]&1)
return false;
match=A[i]/2;
}
if(mp[A[i]]<=mp[match])
{
mp[match]-=mp[A[i]];
mp[A[i]]=0;
}else
return false;
}
}
return true;
}
};
The application of the hash table is actually C++STL: hash_map most of the time, just learn to use it. If you want to understand the hash_map, you can visit: hash_map .