File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments