2007. Find Original Array From Doubled Array
T: O(nlogn + n)
S: O(hash map size + n/2)
class Solution {
// the key is doing in order
public int[] findOriginalArray(int[] changed) {
int n = changed.length;
if (n%2 != 0) {
return new int[]{};
}
Arrays.sort(changed);
Map<Integer, Integer> map = new HashMap<>();
int[] res = new int[n/2];
int idx = 0;
for (int i = n -1; i >= 0 ;i--) {
int twice = changed[i]*2;
if (map.containsKey(twice)) {
int count = map.get(twice);
if (count == 1) {
map.remove(twice);
} else {
map.put(twice, count-1);
}
res[idx++] = changed[i];
} else {
map.put(changed[i], map.getOrDefault(changed[i], 0)+1);
}
}
return idx == n/2 ? res : new int[]{};
}
}
/*
sort
[1,3,4,2,6,8]
from end to 0
map.put 8 1
map.put 6 1
map.put 2 1
4*2 = 8 => remove
3
*/newest explaination
Last updated
Was this helpful?