954. 二倍数对数组
解题思路:根据题目要求,数组A中包含正数、负数和0,所以我们将数组A进行分割排序,然后求解
class Solution {
public:
bool canReorderDoubled(vector<int>& A) {
sort(A.begin(), A.end());
vector<int>positive_number, negative_number;
int zero_nums = 0;
for (auto i = A.begin(); i != A.end(); i++)
{
if (*i > 0)
{
positive_number.push_back(*i);
}
else if (*i < 0)
{
negative_number.push_back(*i);
}
else if (*i == 0)
{
zero_nums++;
}
}
if (positive_number.size() % 2 != 0 || negative_number.size() % 2 != 0 || zero_nums % 2 != 0)
return false;
if (check(positive_number, 1) && check(negative_number, 0))
return true;
return false;
}
bool check(vector<int>nums,bool sign)
{
while (nums.size()!=0)
{
int te = 0;
if (sign)
te = *nums.begin() * 2;
else
{
if (*nums.begin() % 2 == 0)
te = *nums.begin() / 2;
else
return false;
}
auto pos = find(nums.begin(), nums.end(), te);
if (pos != nums.end())
nums.erase(pos), nums.erase(nums.begin());
else
return false;
}
return true;
}
};