An integer array original
is transformed into a doubled array changed
by appending twice the value of every element in original
, and then randomly shuffling the resulting array.
Given an array changed
, return original
if changed
is a doubled array. If changed
is not a doubled array, return an empty array. The elements in original
may be returned in any order.
Example 1:
Input: changed = [1,3,4,2,6,8] Output: [1,3,4] Explanation: One possible original array could be [1,3,4]: - Twice the value of 1 is 1 * 2 = 2. - Twice the value of 3 is 3 * 2 = 6. - Twice the value of 4 is 4 * 2 = 8. Other original arrays could be [4,3,1] or [3,1,4].
Example 2:
Input: changed = [6,3,0,1] Output: [] Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1] Output: [] Explanation: changed is not a doubled array.
Constraints:
1 <= changed.length <= 105
0 <= changed[i] <= 105
思路:// 正着扫描完之后,判断0,很难判断;
// 反着扫描,这样就是高位先遇见记录下来;好处就是比正着扫描好判断;
// 碰见element的时候,hashmap里面有twice,就去掉twice,element啥也不做。
// 如果没有遇见twice,就加入element频率;
class Solution {
public int[] findOriginalArray(int[] changed) {
int n = changed.length;
if(n % 2 != 0) {
return new int[]{};
}
Arrays.sort(changed);
int[] res = new int[n / 2];
int index = 0;
HashMap<Integer, Integer> hashmap = new HashMap<>();
for(int j = n - 1; j >= 0; j--) {
int element = changed[j];
int twice = 2 * element;
// 正着扫描完之后,判断0,很难判断;
// 反着扫描,这样就是高位先遇见记录下来;好处就是比正着扫描好判断;
// 碰见element的时候,hashmap里面有twice,就去掉twice,element啥也不做。
// 如果没有遇见twice,就加入element频率;
if(hashmap.containsKey(twice)) {
if(hashmap.get(twice) == 1) {
hashmap.remove(twice);
}else {
hashmap.put(twice, hashmap.get(twice) - 1);
}
res[index++] = element;
} else {
// !hashmap.containsKey(twice);
hashmap.put(element, hashmap.getOrDefault(element, 0) + 1);
}
}
return index == n / 2 ? res : new int[]{};
}
}