-
Notifications
You must be signed in to change notification settings - Fork 0
/
1054.distant-barcodes.cpp
49 lines (41 loc) · 1.08 KB
/
1054.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
/*
* @lc app=leetcode id=1054 lang=cpp
*
* [1054] Distant Barcodes
*/
// @lc code=start
class Solution
{
public:
vector<int> rearrangeBarcodes(vector<int> &barcodes)
{
using PII = pair<int, int>;
unordered_map<int, int> freq; //{barcode,freq}
for (auto &i : barcodes)
freq[i]++;
priority_queue<PII, vector<PII>, less<>> pq; // {frq , barcode}
for (auto &pii : freq)
pq.push({pii.second, pii.first});
vector<int> res;
res.reserve(barcodes.size());
while (!pq.empty())
{
int k = min((int)pq.size(), 2);
vector<PII> store;
store.reserve(k);
for (int i = 0; i < k; ++i)
{
auto [frq, barcode] = pq.top();
pq.pop();
res.push_back(barcode);
--frq;
if (frq > 0)
store.push_back({frq, barcode});
} //for
for (auto &x : store)
pq.push(x);
} //while
return res;
}
};
// @lc code=end