题目来源:https://leetcode.com/contest/weekly-contest-114/problems/array-of-doubled-pairs/
问题描述
954. 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序列、正数序列分别判断。
------------------------------------------------------------
代码
class Solution {
public:
bool canReorderDoubled(vector<int>& A) {
sort(A.begin(), A.end());
int n = A.size(), i, j, neg = -1, pos = -1, zero = 0;
// neg: position of last negative element, pos: position of first positive element, zero: # of zeros
if (n == 0)
{
return true;
}
vector<int> vis(n, 0);
for (i=0; i<n; i++)
{
if (A[i] < 0)
{
neg = i;
}
else if (A[i] > 0)
{
pos = i;
break;
}
else
{
zero++;
}
}
if (zero % 2 != 0 || (neg != -1 && neg % 2 == 0) || (pos != -1 && (n-pos) % 2 == 1))
{
return false;
}
if (neg != -1)
{
for (i=neg; i>0; i--)
{
if (vis[i] == 0)
{
vis[i] = 1;
for (j=i-1; j>=0; j--)
{
if (vis[j] == 0 && A[j] == 2*A[i])
{
vis[j] = 1;
break;
}
}
if (j == -1)
{
return false;
}
}
}
}
if (pos != -1)
{
for (i=pos; i<n-1; i++)
{
if (vis[i] == 0)
{
vis[i] = 1;
for (j=i+1; j<n; j++)
{
if (vis[j] == 0 && A[j] == 2*A[i])
{
vis[j] = 1;
break;
}
}
if (j == n)
{
return false;
}
}
}
}
return true;
}
};