forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistant Barcodes.cpp
55 lines (42 loc) · 1.28 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
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
struct comp{
bool operator()(pair<int,int>&a, pair<int,int>&b){
return a.first < b.first;
}
};
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
unordered_map<int,int> hmap;
int n = barcodes.size();
if(n==1)return barcodes;
for(auto &bar : barcodes){
hmap[bar]++;
}
vector<int> ans;
priority_queue<pair<int,int>, vector<pair<int,int>>, comp> pq;
for(auto &it : hmap){
pq.push({it.second, it.first});
}
while(pq.size()>1){
auto firstBar = pq.top();
pq.pop();
auto secondBar = pq.top();
pq.pop();
ans.push_back(firstBar.second);
ans.push_back(secondBar.second);
--firstBar.first;
--secondBar.first;
if(firstBar.first > 0){
pq.push(firstBar);
}
if(secondBar.first > 0){
pq.push(secondBar);
}
}
if(pq.size()){
ans.push_back(pq.top().second);
pq.pop();
}
return ans;
}
};