LeetCode 题解工作台
字典序排数
给你一个整数 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] 提…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 图·搜索
答案摘要
我们首先定义一个变量 ,初始时 $v = 1$。然后我们从 开始迭代,每次迭代都将 添加到答案数组中。然后,如果 $v \times 10 \leq n$,我们将 更新为 $v \times 10$;否则,如果 $v \bmod 10 = 9$ 或者 $v + 1 > n$,我们就循环将 除以 。循环结束后,我们将 加一。继续迭代,直到我们添加了 个数到答案数组中。 时间复杂度 ,其中…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
给你一个整数 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
解题思路
方法一:迭代
我们首先定义一个变量 ,初始时 。然后我们从 开始迭代,每次迭代都将 添加到答案数组中。然后,如果 ,我们将 更新为 ;否则,如果 或者 ,我们就循环将 除以 。循环结束后,我们将 加一。继续迭代,直到我们添加了 个数到答案数组中。
时间复杂度 ,其中 是给定的整数 。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
ans = []
v = 1
for _ in range(n):
ans.append(v)
if v * 10 <= n:
v *= 10
else:
while v % 10 == 9 or v + 1 > n:
v //= 10
v += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each number from 1 to n is visited exactly once during DFS traversal. Space complexity is O(1) beyond the output list since only a single integer is tracked during iteration or recursion, avoiding extra data structures. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Asks how to generate numbers without sorting the final list.
- question_mark
Checks understanding of DFS traversal applied to number prefixes.
- question_mark
Tests ability to optimize space usage for large n values.
常见陷阱
外企场景- error
Forgetting to stop recursion when the number exceeds n.
- error
Using built-in sort instead of generating numbers lexicographically.
- error
Exceeding space limits by storing unnecessary intermediate data structures.
进阶变体
外企场景- arrow_right_alt
Generate numbers in reverse lexicographical order using the same DFS-trie pattern.
- arrow_right_alt
Limit the output to numbers containing a specific digit while maintaining lexicographical order.
- arrow_right_alt
Adapt the approach for a range [m, n] instead of starting from 1, adjusting prefix exploration accordingly.