1. 程式人生 > >114th LeetCode Weekly Contest Array of Doubled Pairs

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:

  1. 0 <= A.length <= 30000
  2. A.length is even
  3. -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; } };