Skip to content

Commit 71684e2

Browse files
authored
Create array-of-doubled-pairs.cpp
1 parent 1c6e754 commit 71684e2

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

C++/array-of-doubled-pairs.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(n + klogk)
2+
// Space: O(k)
3+
4+
class Solution {
5+
public:
6+
bool canReorderDoubled(vector<int>& A) {
7+
unordered_map<int, int> count;
8+
for (const auto& x : A) {
9+
++count[x];
10+
}
11+
vector<int> keys;
12+
for (const auto& kvp : count) {
13+
keys.emplace_back(kvp.first);
14+
}
15+
sort(keys.begin(), keys.end(),
16+
[](int i, int j) {
17+
return abs(i) < abs(j);
18+
});
19+
for (const auto& x : keys) {
20+
if (count[x] > count[2 * x]) {
21+
return false;
22+
}
23+
count[2 * x] -= count[x];
24+
}
25+
return true;
26+
}
27+
};

0 commit comments

Comments
 (0)