forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexicographical-numbers.py
More file actions
37 lines (29 loc) · 870 Bytes
/
lexicographical-numbers.py
File metadata and controls
37 lines (29 loc) · 870 Bytes
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
# Time: O(n)
# Space: O(1)
# Given an integer n, return 1 - n in lexicographical order.
#
# For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
#
# Please optimize your algorithm to use less time and space.
# The input size may be as large as 5,000,000.
class Solution(object):
def lexicalOrder(self, n):
result = []
i = 1
while len(result) < n:
k = 0
while i * 10**k <= n:
result.append(i * 10**k)
k += 1
num = result[-1] + 1
while num <= n and num % 10:
result.append(num)
num += 1
if not num % 10:
num -= 1
else:
num /= 10
while num % 10 == 9:
num /= 10
i = num+1
return result