forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k-th-smallest-in-lexicographical-order.py
102 lines (91 loc) · 2.55 KB
/
k-th-smallest-in-lexicographical-order.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# Time: O(logn)
# Space: O(logn)
# Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
#
# Note: 1 <= k <= n <= 109.
#
# Example:
#
# Input:
# n: 13 k: 2
#
# Output:
# 10
#
# Explanation:
# The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],
# so the second smallest number is 10.
class Solution(object):
def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
result = 0
cnts = [0] * 10
for i in xrange(1, 10):
cnts[i] = cnts[i - 1] * 10 + 1
nums = []
i = n
while i:
nums.append(i % 10)
i /= 10
total, target = n, 0
i = len(nums) - 1
while i >= 0 and k > 0:
target = target*10 + nums[i]
start = int(i == len(nums)-1)
for j in xrange(start, 10):
candidate = result*10 + j
if candidate < target:
num = cnts[i+1]
elif candidate > target:
num = cnts[i]
else:
num = total - cnts[i + 1]*(j-start) - cnts[i]*(9-j)
if k > num:
k -= num
else:
result = candidate
k -= 1
total = num-1
break
i -= 1
return result
# Time: O(logn * logn)
# Space: O(logn)
class Solution2(object):
def findKthNumber(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
def count(n, prefix):
result, number = 0, 1
while prefix <= n:
result += number
prefix *= 10
number *= 10
result -= max(number/10 - (n - prefix/10 + 1), 0)
return result
def findKthNumberHelper(n, k, cur, index):
if cur:
index += 1
if index == k:
return (cur, index)
i = int(cur == 0)
while i <= 9:
cur = cur * 10 + i
cnt = count(n, cur)
if k > cnt + index:
index += cnt
elif cur <= n:
result = findKthNumberHelper(n, k, cur, index)
if result[0]:
return result
i += 1
cur /= 10
return (0, index)
return findKthNumberHelper(n, k, 0, 0)[0]