给定一个长度为偶数的整数数组 A
,只有对 A
进行重组后可以满足 “对于每个 0 <= i < len(A) / 2
,都有 A[2 * i + 1] = 2 * A[2 * i]
” 时,返回 true
;否则,返回 false
。
示例 1:
输入:[3,1,3,6]
输出:false
示例 2:
输入:[2,1,2,6]
输出:false
示例 3:
输入:[4,-2,2,-4]
输出:true
解释:我们可以用 [-2,-4] 和 [2,4] 这两组组成 [-2,-4,2,4] 或是 [2,4,-2,-4]
示例 4:
输入:[1,2,4,16,8,4]
输出:false
提示:
0 <= A.length <= 30000
A.length
为偶数
-100000 <= A[i] <= 100000
C++
class Solution {
public:
bool judge(map<int,int>& pos)
{
for(auto it:pos)
{
if(it.second)
{
if(it.first%2)
{
return false;
}
else
{
int count=pos[it.first/2];
if(count<it.second)
{
return false;
}
else
{
pos[it.first/2]-=it.second;
pos[it.first]=0;
}
}
}
}
return true;
}
bool canReorderDoubled(vector<int>& A)
{
int n=A.size();
map<int,int> pos;
map<int,int> neg;
int count_zero=0;
for(int i=0;i<n;i++)
{
if(A[i]<0)
{
neg[A[i]]++;
}
else if(A[i]>0)
{
pos[-A[i]]++;
}
else
{
count_zero++;
}
}
if(count_zero%2)
{
return false;
}
if(!judge(pos))
{
return false;
}
if(!judge(neg))
{
return false;
}
return true;
}
};
python
class Solution:
def judge(self, tmp):
for key in tmp:
if tmp[key]:
if key%2:
return False
else:
val=key//2
if val in tmp:
count=tmp[val]
if count<tmp[key]:
return False
else:
tmp[val]-=tmp[key]
else:
return False
return True
def canReorderDoubled(self, A: List[int]) -> bool:
n=len(A)
pos={}
neg={}
count_zero=0
for i in range(n):
if A[i]>0:
if A[i] not in pos:
pos[A[i]]=1
else:
pos[A[i]]+=1
elif A[i]<0:
if -A[i] not in neg:
neg[-A[i]]=1
else:
neg[-A[i]]+=1
else:
count_zero+=1
if 1==count_zero%2:
return False
pos=dict(sorted(pos.items(),key=lambda x:-x[0]))
neg=dict(sorted(neg.items(),key=lambda x:-x[0]))
if self.judge(pos) and self.judge(neg):
return True
return False