Skip to content

Commit 275584b

Browse files
committed
refactor: solution 440. K-th Smallest in Lexicographical Order
1 parent b47ec18 commit 275584b

File tree

2 files changed

+29
-21
lines changed

2 files changed

+29
-21
lines changed

solutions/440. K-th Smallest in Lexicographical Order/README.md

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
**Solution: `Trie`**
3434

35-
- Time complexity: <em>O((logn)<sup>2</sup>)</em>
35+
- Time complexity: <em>O(log<sup>2</sup>n)</em>
3636
- Space complexity: <em>O(1)</em>
3737

3838
<p>&nbsp;</p>
@@ -48,30 +48,34 @@
4848
const findKthNumber = function (n, k) {
4949
let current = 1;
5050

51-
const getGap = (left, right) => {
51+
const getGap = num => {
52+
let start = num;
53+
let end = num + 1;
5254
let gap = 0;
5355

54-
while (left <= n) {
55-
gap += Math.min(n + 1, right) - left;
56-
left *= 10;
57-
right *= 10;
56+
while (start <= n) {
57+
gap += Math.min(n + 1, end) - start;
58+
start *= 10;
59+
end *= 10;
5860
}
61+
5962
return gap;
6063
};
6164

6265
k -= 1;
6366

6467
while (k) {
65-
const gap = getGap(current, current + 1);
68+
const gap = getGap(current);
6669

6770
if (gap <= k) {
68-
k -= gap;
6971
current += 1;
70-
continue;
72+
k -= gap;
73+
} else {
74+
current *= 10;
75+
k -= 1;
7176
}
72-
current *= 10;
73-
k -= 1;
7477
}
78+
7579
return current;
7680
};
7781
```

solutions/440. K-th Smallest in Lexicographical Order/solution.js

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,29 +6,33 @@
66
const findKthNumber = function (n, k) {
77
let current = 1;
88

9-
const getGap = (left, right) => {
9+
const getGap = num => {
10+
let start = num;
11+
let end = num + 1;
1012
let gap = 0;
1113

12-
while (left <= n) {
13-
gap += Math.min(n + 1, right) - left;
14-
left *= 10;
15-
right *= 10;
14+
while (start <= n) {
15+
gap += Math.min(n + 1, end) - start;
16+
start *= 10;
17+
end *= 10;
1618
}
19+
1720
return gap;
1821
};
1922

2023
k -= 1;
2124

2225
while (k) {
23-
const gap = getGap(current, current + 1);
26+
const gap = getGap(current);
2427

2528
if (gap <= k) {
26-
k -= gap;
2729
current += 1;
28-
continue;
30+
k -= gap;
31+
} else {
32+
current *= 10;
33+
k -= 1;
2934
}
30-
current *= 10;
31-
k -= 1;
3235
}
36+
3337
return current;
3438
};

0 commit comments

Comments
 (0)