386. Lexicographical Numbers
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
Example:
- Input: n = 32
- Output: [1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,4,5,6,7,8,9]
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
res = [0] * n
cur = 1
for i in range(n):
res[i] = cur
if cur * 10 <= n:
cur *= 10
else:
if cur == n:
cur //= 10
cur += 1
while cur % 10 == 0:
cur //= 10
return res