Skip to content

Commit c3280b7

Browse files
Time: 44 ms (80.68%), Space: 13.3 MB (32.39%) - LeetHub
1 parent acd698c commit c3280b7

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
vector<pair<int, int>> resort;
3+
4+
priority_queue<int, vector<int>, greater<int>> nums[10];
5+
int used[30001];
6+
int n;
7+
int getSum(int index) {
8+
int sum = 0;
9+
while (index > 0) {
10+
sum += used[index];
11+
index -= index & (-index);
12+
}
13+
return sum;
14+
}
15+
16+
void updateBIT(int index, int val)
17+
{
18+
while (index <= n)
19+
{
20+
used[index] += val;
21+
index += index & (-index);
22+
}
23+
}
24+
25+
public:
26+
string minInteger(string num, int k) {
27+
memset(used, 0, sizeof(used));
28+
29+
int ctr = 0;
30+
n = num.size();
31+
for (int i = 0; i < n; i++) {
32+
nums[num[i] - '0'].push(i + 1);
33+
}
34+
string res;
35+
while (ctr < n && k > 0) {
36+
for (int i = 0; i <= 9; i++) {
37+
if (!nums[i].empty()) {
38+
int cur = nums[i].top();
39+
40+
int holes = getSum(cur - 1);
41+
int act = cur - holes;
42+
if (act - 1 <= k) {
43+
res += ('0' + i);
44+
k -= (act - 1);
45+
updateBIT(cur, 1);
46+
nums[i].pop();
47+
break;
48+
}
49+
}
50+
}
51+
ctr++;
52+
}
53+
54+
for(int i = 0; i <= 9; i++) {
55+
while (!nums[i].empty()) {
56+
resort.emplace_back(nums[i].top(), i);
57+
nums[i].pop();
58+
}
59+
}
60+
61+
sort(resort.begin(), resort.end());
62+
for (auto &p : resort) {
63+
res += ('0' + p.second);
64+
}
65+
return res;
66+
}
67+
};

0 commit comments

Comments
 (0)