Leetcode笔记 每日一题 386. 字典序排数 (22.04.18)
Leetcode 每日一题 386. 字典序排数(22.04.18)
一、题目
给你一个整数 n ,按字典序返回范围 [1, n] 内所有整数。
你必须设计一个时间复杂度为 O(n) 且使用 O(1) 额外空间的算法。
示例 1:
输入:n = 13
输出:[1,10,11,12,13,2,3,4,5,6,7,8,9]
示例 2:
输入:n = 2
输出:[1,2]
提示:
1 <= n <= 5 * 104
二、解题思路
(一)方法一:排序
思路: 将要排序的数字转成字符串排序,最后再转换为整数类型。 因为字符串是按ASCII码值的大小进行的。
Python代码
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
res = []
for i in range(1, n+1):
res.append(str(i))
res.sort() # 字符串排序
res = [int(x) for x in res]
return res
(二)方法二:深度优先(dfs)
这道题跟3.28的 Leetcode 每日一题 440. 字典序的第K小数字 (22.03.23) 有点相像,都是按字典序进行排序。
思路: 考虑用前序+dfs。
Python代码
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
res = []
num = 1
for i in range(n):
res.append(num)
if num * 10 <= n:
num *= 10
else:
while num % 10 == 9 or num + 1 > n:
num //= 10
num += 1
return res