-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtoggle-light-bulbs.cpp
More file actions
42 lines (40 loc) · 947 Bytes
/
toggle-light-bulbs.cpp
File metadata and controls
42 lines (40 loc) · 947 Bytes
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
37
38
39
40
41
42
// Time: O(n + r)
// Space: O(r)
// freq table, counting sort
class Solution {
public:
vector<int> toggleLightBulbs(vector<int>& bulbs) {
const auto& mx = ranges::max(bulbs);
vector<int> cnt(mx + 1);
for (const auto& x : bulbs) {
cnt[x] ^= 1;
}
vector<int> result;
for (int i = 1; i <= mx; ++i) {
if (cnt[i]) {
result.emplace_back(i);
}
}
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
// freq table, sort
class Solution2 {
public:
vector<int> toggleLightBulbs(vector<int>& bulbs) {
unordered_map<int, int> cnt;
for (const auto& x : bulbs) {
cnt[x] ^= 1;
}
vector<int> result;
for (const auto& [k, v] : cnt) {
if (v) {
result.emplace_back(k);
}
}
ranges::sort(result);
return result;
}
};