-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimumPossibleIntegerAfteratMostKAdjacentSwapsOnDigits.cpp
More file actions
62 lines (56 loc) · 1.43 KB
/
minimumPossibleIntegerAfteratMostKAdjacentSwapsOnDigits.cpp
File metadata and controls
62 lines (56 loc) · 1.43 KB
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
56
57
58
59
60
61
62
// Source: https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/
// Author: Miao Zhang
// Date: 2021-05-12
class Fenwick {
public:
Fenwick(int n): sums_(n + 1) {}
void update(int i , int delta) {
i++;
while (i < sums_.size()) {
sums_[i] += delta;
i += i & -i;
}
}
int query(int i) {
i++;
int res = 0;
while (i > 0) {
res += sums_[i];
i -= i & -i;
}
return res;
}
private:
vector<int> sums_;
};
class Solution {
public:
string minInteger(string num, int k) {
int n = num.size();
vector<queue<int>> pos(10);
for (int i = 0; i < n; i++) {
pos[num[i] - '0'].push(i);
}
Fenwick tree(n);
vector<int> seen(n);
string res;
while (k > 0 && res.size() < n) {
for (int d = 0; d < 10; d++) {
if (pos[d].empty()) continue;
int i = pos[d].front();
int cost = i - tree.query(i - 1);
if (cost > k) continue;
k -= cost;
res += ('0' + d);
tree.update(i, 1);
seen[i] = 1;
pos[d].pop();
break;
}
}
for (int i = 0; i < num.size(); i++) {
if (!seen[i]) res += num[i];
}
return res;
}
};