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
1 class Solution { 2 public boolean canReorderDoubled(int[] A) { 3 Map<Integer, Integer> map = new HashMap<>(); 4 for (int item : A) { 5 if (item == 0) { 6 continue; 7 } 8 map.put(item, map.getOrDefault(item, 0) + 1); 9 } 10 Arrays.sort(A); 11 for (int i = 0; i < A.length; i++) { 12 if (A[i] != 0 && map.get(A[i]) < 0) { 13 return false; 14 } 15 if (A[i] != 0 && map.get(A[i]) > 0) { 16 int target = A[i] * 2; 17 if (A[i] < 0) { 18 if (A[i] % 2 != 0) { 19 return false; 20 } else { 21 target = A[i] / 2; 22 } 23 } 24 if (!map.containsKey(target)) { 25 return false; 26 } 27 map.put(target, map.get(target) - map.get(A[i])); 28 map.put(A[i], 0); 29 } 30 } 31 return true; 32 } 33 }