Skip to content

Commit 41782ab

Browse files
authored
Update 1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js
1 parent df68b8a commit 41782ab

File tree

1 file changed

+21
-29
lines changed

1 file changed

+21
-29
lines changed

1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js

Lines changed: 21 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,28 @@
44
* @return {string}
55
*/
66
const minInteger = function (num, k) {
7-
const nums = num.split("")
8-
const map = {}
9-
nums.forEach((n, i) => {
10-
map[n] = map[n] || []
11-
map[n].push(i)
12-
})
13-
14-
const used = new Set()
7+
const nums = num.split('')
8+
const len = nums.length
9+
const q = Array(10)
10+
.fill(null)
11+
.map(() => [])
12+
nums.forEach((n, i) => q[+n].push(i))
1513
const tree = new Fenwick(nums.length)
16-
let idx = 0
17-
let re = ""
18-
while (k > 0 && idx < nums.length) {
19-
for (let i = 0; i < 10; i++) {
20-
if (!map[i] || !map[i].length) continue
21-
const id = map[i][0]
22-
const cost = id - tree.query(id)
23-
if (k < cost) continue
24-
re += nums[id]
25-
k -= cost
26-
used.add(id)
27-
tree.update(id + 1, 1)
28-
map[i].shift()
29-
break
30-
}
31-
idx++
32-
}
33-
34-
for (let i = 0; i < nums.length; i++) {
35-
if (!used.has(i)) {
36-
re += nums[i]
14+
for (let i = 1; i <= len; i++) tree.update(i, 1)
15+
let re = ''
16+
for (let i = 0; i < len; i++) {
17+
for (let j = 0; j <= 9; j++) {
18+
const idxArr = q[j]
19+
if (idxArr && idxArr.length) {
20+
const idx = idxArr[0]
21+
const num = tree.query(idx)
22+
if (num > k) continue
23+
k -= num
24+
idxArr.shift()
25+
tree.update(idx + 1, -1)
26+
re += j
27+
break
28+
}
3729
}
3830
}
3931

0 commit comments

Comments
 (0)