forked from black-shadows/LeetCode-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistant-barcodes.cpp
30 lines (28 loc) · 895 Bytes
/
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
// Time: O(klogk), k is the number of distinct barcode
// Space: O(k)
class Solution {
public:
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
unordered_map<int, int> cnts;
for (const auto& barcode : barcodes) {
++cnts[barcode];
}
vector<pair<int, int>> sorted_cnts;
for (const auto& kvp : cnts) {
sorted_cnts.emplace_back(kvp.second, kvp.first);
}
sort(sorted_cnts.begin(), sorted_cnts.end(),
greater<pair<int, int>>());
int i = 0;
for (const auto& kvp : sorted_cnts) {
for (int j = 0; j < kvp.first; ++j) {
barcodes[i] = kvp.second;
i += 2;
if (i >= barcodes.size()) {
i = 1;
}
}
}
return barcodes;
}
};