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
题目理解:
给定一个数组,将这个数组分成若干个对(a,b),每一个对要满足a * 2 = b,问给定数组能够完成划分。
解题思路:
正数乘以2还是正数,负数乘以2还是负数,但是正数会变小,负数会变大,因此将正负数分开来处理。
在处理正数时,可以首先对所有正数进行递增排序,然后使用两个指针left和right,left指向每一个对中的第一个数a,right指向第二个数b,固定left,然后将right每次增大1,检查是否符合要求,如果right > 2 * left,那么right之后的数字也不可能满足当前的left,因此不存在。如果找到了对应的left,那么将left增大1,继续找right。对于正数a1,a2,如果a1 < a2,那么a1 * 2 < a2 * 2,因此无论是left指针还是right指针,都可以一直增大,不需要检查其前面的数字。
处理负数的方法大致相同,但是负数乘以2之后会变小,因此首先按照递减序排序,然后再使用相同的方法,判断能够对负数进行划分。
class Solution {
public boolean canReorderDoubled(int[] A) {
List<Integer> plus = new ArrayList<>(), minus = new ArrayList<>();
for(int num : A)
if(num < 0)
minus.add(num);
else
plus.add(num);
Collections.sort(plus);
Collections.sort(minus, Collections.reverseOrder());
if(plus.size() % 2 == 1 || minus.size() % 2 == 1)
return false;
int left = 0, right = 1;
int len = plus.size();
boolean[] visited = new boolean[len];
while(left < len){
while(right < len && plus.get(left) * 2 > plus.get(right))
right++;
//System.out.println(left + " " + right);
if(right >= len || plus.get(left) * 2 != plus.get(right))
return false;
visited[right] = true;
visited[left] = true;
right++;
while(left < len && visited[left])
left++;
}
len = minus.size();
left = 0;
right = 1;
visited = new boolean[len];
while(left < len){
while(right < len && minus.get(left) * 2 < minus.get(right))
right++;
if(right >= len || minus.get(left) * 2 != minus.get(right))
return false;
visited[left] = true;
visited[right] = true;
right++;
while(left < len && visited[left])
left++;
}
return true;
}
}