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
Idea 1. Kind of counting sort + hashMap
Time complexity: O(n + m) where m = max(A), n = A.length
Space complexity: O(m)
1 class Solution { 2 public boolean canReorderDoubled(int[] A) { 3 int n = 20000; 4 int[] negatives = new int[n+1]; 5 int[] positives = new int[n+1]; 6 7 for(int a: A) { 8 if(a < 0) { 9 ++negatives[-a]; 10 } 11 else { 12 ++positives[a]; 13 } 14 } 15 16 for(int i = 0; i <= n; ++i) { 17 if(negatives[i] != 0) { 18 if(negatives[2*i] < negatives[i]) { 19 return false; 20 } 21 else { 22 negatives[2*i] -= negatives[i]; 23 } 24 } 25 26 if(positives[i] != 0) { 27 if(positives[2*i] < positives[i]) { 28 return false; 29 } 30 else { 31 positives[2*i] -= positives[i]; 32 } 33 } 34 } 35 36 37 return true; 38 } 39 }
Idea 1.a TreeMap + absoluate value as comparator, no need to deal with /2 for negative values
Time complexity: O(nlogn)
Space complexity: O(n)
1 class Solution { 2 public boolean canReorderDoubled(int[] A) { 3 Comparator<Integer> comparator = (Integer a, Integer b) -> { 4 int absEqual = Integer.compare(Math.abs(a), Math.abs(b)); 5 if(absEqual == 0 && a != b) { 6 return Integer.compare(a, b); 7 } 8 return absEqual; 9 }; 10 11 Map<Integer, Integer> count = new TreeMap<>(comparator); 12 13 for(int a : A) { 14 count.put(a, count.getOrDefault(a, 0) + 1); 15 } 16 17 for(int key: count.keySet()) { 18 int want = count.getOrDefault(2*key, 0); 19 if(count.get(key) > want) { 20 return false; 21 } 22 else if(count.containsKey(2*key)) { 23 count.put(2*key, want - count.get(key)); 24 } 25 } 26 27 return true; 28 } 29 }
Idea1.c normal treeMap with both positive + negatives
1 class Solution { 2 public boolean canReorderDoubled(int[] A) { 3 Map<Integer, Integer> count = new TreeMap<>(); 4 5 for(int a : A) { 6 count.put(a, count.getOrDefault(a, 0) + 1); 7 } 8 9 for(int key: count.keySet()) { 10 if(count.get(key) == 0) { 11 continue; 12 } 13 14 int next = key < 0? key/2 : key*2; 15 int want = count.getOrDefault(next, 0); 16 if(count.get(key) > want) { 17 return false; 18 } 19 20 count.put(next, want - count.get(key)); 21 22 } 23 24 return true; 25 } 26 }