954. 二倍数对数组
难度中等32收藏分享切换为英文接收动态反馈
给定一个长度为偶数的整数数组 A,只有对 A 进行重组后可以满足 “对于每个 0 <= i < len(A) / 2,都有 A[2 * i + 1] = 2 * A[2 * i]” 时,返回 true;否则,返回 false。
题解:分类+map(应该用hash_map的,但是不知为什么hash_map在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; } };哈希表的应用其实大多数时候是C++STL:hash_map,学会应用就好了,想要了解hash_map的可以访问:hash_map。
