File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/
3
+ * Primary idea: Image it is a ten-deminsion tree, we only need to calculate the number
4
+ * of children for each node, and keep minus until we get the right one
5
+ *
6
+ * Note: Swift does not have a way to access a character in a string with O(1),
7
+ * thus we have to first transfer the string to a character array
8
+ * Time Complexity: O(n), Space Complexity: O(1)
9
+ *
10
+ */
11
+
12
+ class KthSmallestLexicographicalOrder {
13
+ func findKthNumber( _ n: Int , _ k: Int ) -> Int {
14
+ var curt = 1 , k = k - 1
15
+
16
+ while k > 0 {
17
+ var step = 0 , first = curt, last = curt + 1
18
+ while first <= n {
19
+ step += min ( n + 1 , last) - first
20
+ first *= 10
21
+ last *= 10
22
+ }
23
+ if step <= k {
24
+ curt += 1
25
+ k -= step
26
+ } else {
27
+ curt *= 10
28
+ k -= 1
29
+ }
30
+ }
31
+
32
+ return curt
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments