954. Array of Doubled Pairs
T: O(nlogn + n)
S: O(|hashMap size|)class Solution {
public boolean canReorderDoubled(int[] arr) {
Arrays.sort(arr);
Map<Integer, Integer> map = new HashMap();
for (int num : arr) {
map.put(num, map.getOrDefault(num, 0)+1);
}
for (int num : arr) {
if (map.get(num) == 0) {
continue;
}
if (num < 0 && num % 2 != 0) { // for [-5,-2], cant cal -5/2 = ??
return false;
}
// negative sort 後會長這樣: -4 -2, 所以要 num/2
int doubledNum = num < 0 ? num/2 : num*2;
// 找不到對應的 double number
if (map.getOrDefault(doubledNum, 0) == 0) {
return false;
}
// 都找到 count--
map.put(num, map.get(num) - 1);
map.put(doubledNum, map.get(doubledNum) - 1);
}
return true;
}
}
/*
因為沒有要求輸出結果順序, 只是要 true or false
所以一樣的解法可以(leetcode 2007
sort array first
build map
so if small can build large (find in hashmap), map both cnt--
需要注意的是 num < 0 時, 是 num/2, 其他是 num*2
所以也要注意負數一定是偶數, 不然無法 num/2
if (num < 0 && num % 2 != 0) { // for [-5,-2], cant cal -5/2 = ??
T: O(nlogn + n)
S: O(|hashMap size|)
*/use idea same as 2007
Last updated
