[LeetCode] Array of Doubled Pairs

954. Array of Doubled Pairs

Given an array of integers arr of even length, return true if and only if it is possible to reorder it such that arr[2 i + 1] = 2 arr[2 * i] for every 0 <= i < len(arr) / 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
bool canReorderDoubled(vector<int>& arr) {
unordered_map<int, int> m;
int maxVal = 0;
for(auto& num : arr) {
m[num]++;
maxVal = max(maxVal, abs(num));
}
maxVal = (maxVal + 1) >> 1;
for(int i = 0; i <= maxVal; i++) {
if(m.count(i) && m[i]) {
if(m.count(i*2) && m[i*2] >= m[i]) {
m[i*2] -= m[i];
m.erase(i);
if(!m[i*2])
m.erase(i*2);
} else {
return false;
}
}
if(m.count(-i) && m[-i]) {
if(m.count(-i*2) && m[-i*2] >= m[-i]) {
m[-i*2] -= m[-i];
m.erase(-i);
if(!m[-i*2])
m.erase(-i*2);
} else {
return false;
}
}
}
return m.empty();
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/30/PS/LeetCode/array-of-doubled-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.