-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdistant_barcodes.cpp
43 lines (35 loc) · 1.06 KB
/
distant_barcodes.cpp
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
43
class Solution {
public:
// O(N * log N)
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
priority_queue<pair<int, int> > maxHeap;
unordered_map<int, int> count;
for(auto &barcode : barcodes) {
count[barcode]++;
}
for(auto &[k, v] : count) {
maxHeap.push({v, k});
}
vector<int> result;
pair<int, int> current, next;
while(!maxHeap.empty()) {
current = maxHeap.top();
maxHeap.pop();
current.first -= 1;
result.push_back(current.second);
if(!maxHeap.empty()) {
next = maxHeap.top();
maxHeap.pop();
next.first -= 1;
result.push_back(next.second);
}
if(current.first > 0) {
maxHeap.push(current);
}
if(next.first > 0) {
maxHeap.push(next);
}
}
return result;
}
};