File tree Expand file tree Collapse file tree 2 files changed +29
-21
lines changed
solutions/440. K-th Smallest in Lexicographical Order Expand file tree Collapse file tree 2 files changed +29
-21
lines changed Original file line number Diff line number Diff line change 32
32
33
33
** Solution: ` Trie ` **
34
34
35
- - Time complexity: <em >O((logn) <sup >2</sup >)</em >
35
+ - Time complexity: <em >O(log <sup >2</sup >n )</em >
36
36
- Space complexity: <em >O(1)</em >
37
37
38
38
<p >  ; </p >
48
48
const findKthNumber = function (n , k ) {
49
49
let current = 1 ;
50
50
51
- const getGap = (left , right ) => {
51
+ const getGap = num => {
52
+ let start = num;
53
+ let end = num + 1 ;
52
54
let gap = 0 ;
53
55
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 ;
58
60
}
61
+
59
62
return gap;
60
63
};
61
64
62
65
k -= 1 ;
63
66
64
67
while (k) {
65
- const gap = getGap (current, current + 1 );
68
+ const gap = getGap (current);
66
69
67
70
if (gap <= k) {
68
- k -= gap;
69
71
current += 1 ;
70
- continue ;
72
+ k -= gap;
73
+ } else {
74
+ current *= 10 ;
75
+ k -= 1 ;
71
76
}
72
- current *= 10 ;
73
- k -= 1 ;
74
77
}
78
+
75
79
return current;
76
80
};
77
81
```
Original file line number Diff line number Diff line change 6
6
const findKthNumber = function ( n , k ) {
7
7
let current = 1 ;
8
8
9
- const getGap = ( left , right ) => {
9
+ const getGap = num => {
10
+ let start = num ;
11
+ let end = num + 1 ;
10
12
let gap = 0 ;
11
13
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 ;
16
18
}
19
+
17
20
return gap ;
18
21
} ;
19
22
20
23
k -= 1 ;
21
24
22
25
while ( k ) {
23
- const gap = getGap ( current , current + 1 ) ;
26
+ const gap = getGap ( current ) ;
24
27
25
28
if ( gap <= k ) {
26
- k -= gap ;
27
29
current += 1 ;
28
- continue ;
30
+ k -= gap ;
31
+ } else {
32
+ current *= 10 ;
33
+ k -= 1 ;
29
34
}
30
- current *= 10 ;
31
- k -= 1 ;
32
35
}
36
+
33
37
return current ;
34
38
} ;
You can’t perform that action at this time.
0 commit comments