Skip to content

Commit e9ecdfd

Browse files
Create distant_barcodes.cpp
1 parent b5070aa commit e9ecdfd

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

distant_barcodes.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
public:
3+
4+
// O(N * log N)
5+
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
6+
7+
priority_queue<pair<int, int> > maxHeap;
8+
unordered_map<int, int> count;
9+
for(auto &barcode : barcodes) {
10+
count[barcode]++;
11+
}
12+
13+
for(auto &[k, v] : count) {
14+
maxHeap.push({v, k});
15+
}
16+
17+
vector<int> result;
18+
pair<int, int> current, next;
19+
20+
while(!maxHeap.empty()) {
21+
current = maxHeap.top();
22+
maxHeap.pop();
23+
current.first -= 1;
24+
result.push_back(current.second);
25+
26+
if(!maxHeap.empty()) {
27+
next = maxHeap.top();
28+
maxHeap.pop();
29+
next.first -= 1;
30+
result.push_back(next.second);
31+
}
32+
33+
if(current.first > 0) {
34+
maxHeap.push(current);
35+
}
36+
if(next.first > 0) {
37+
maxHeap.push(next);
38+
}
39+
}
40+
41+
return result;
42+
}
43+
};

0 commit comments

Comments
 (0)