114th LeetCode Weekly Contest Array of Doubled Pairs
Given an array of integers A
with even length, return true
if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i]
for every 0 <= i < len(A) / 2
.
Example 1:
Input: [3,1,3,6]
Output: false
Example 2:
Input: [2,1,2,6]
Output: false
Example 3:
Input: [4,-2,2,-4]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
Example 4:
Input: [1,2,4,16,8,4]
Output: false
Note:
0 <= A.length <= 30000
A.length
is even-100000 <= A[i] <= 100000
题目很短,题意很明显,说一下思路吧
首先得分出正数和负数,0就不管了都是0,正数是小到大,负数则反过来,然后我们只找两个数字一组,为什么是两个数字呢
如果是2 4 4 8,把2,4,8找了,那还有个4怎么办,所以应该是2,4 4,8就可以了
操作就是拿出现的数字*2去看有没有这个数,最后是否还留下数字
class Solution { public: bool canReorderDoubled(vector<int>& A) { sort(A.begin(),A.end()); int len = A.size(); map<int,int>Mp; vector<int>Ve1; vector<int>Ve2; vector<int>Ve; set<int>Se; int num; for(int i=0;i<len;i++){ Mp[A[i]]++; if(A[i]>0){ Ve1.push_back(A[i]); } if(A[i]<0){ Ve2.push_back(A[i]); } } int len1 = Ve1.size(); for(int i=0;i<len1;i++){ Ve.clear(); num = Ve1[i]; while(Mp[num]>0){ Mp[num]--; Ve.push_back(num); num*=2; if(Ve.size()==2){ break; } } for(int j=0;j<Ve.size();j++){ //cout<<Ve[j]<<" "; } //cout<<endl; if(Ve.size()==1){ Mp[Ve1[i]]++; } } int len2 = Ve2.size(); for(int i=len2-1;i>=0;i--){ Ve.clear(); num = Ve2[i]; while(Mp[num]>0){ Mp[num]--; Ve.push_back(num); num*=2; if(Ve.size()==2){ break; } } for(int j=0;j<Ve.size();j++){ //cout<<Ve[j]<<" "; } //cout<<endl; if(Ve.size()==1){ Mp[Ve2[i]]++; } } for(int i=0;i<len;i++){ //cout<<Mp[A[i]]<<"A"<<endl; if(Mp[A[i]]&&A[i]!=0){ return false; } } return true; } };