LeetCode 题解工作台
顺次数
我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。 请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。 示例 1: 输出: low = 100, high = 300 输出: [123,234] 示例 2: 输出: low = 1000, h…
1
题型
5
代码语言
3
相关题
当前训练重点
中等 · Enumeration-driven solution strategy
答案摘要
我们可以枚举数字的第一位 ,然后枚举数字的最后一位 ,那么这个数字就是 这 个数字组成的。我们可以通过不断地将数字乘以 并加上下一个数字 来得到下一个数字,如果数字在 $[low, high]$ 的范围内,我们就将它加入答案中。 枚举结束后,我们将答案数组排序并返回即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Enumeration-driven solution strategy 题型思路
题目描述
我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。
请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。
示例 1:
输出:low = 100, high = 300 输出:[123,234]
示例 2:
输出:low = 1000, high = 13000 输出:[1234,2345,3456,4567,5678,6789,12345]
提示:
10 <= low <= high <= 10^9
解题思路
方法一:枚举
我们可以枚举数字的第一位 ,然后枚举数字的最后一位 ,那么这个数字就是 这 个数字组成的。我们可以通过不断地将数字乘以 并加上下一个数字 来得到下一个数字,如果数字在 的范围内,我们就将它加入答案中。
枚举结束后,我们将答案数组排序并返回即可。
时间复杂度近似 ,空间复杂度 。
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
ans = []
for i in range(1, 9):
x = i
for j in range(i + 1, 10):
x = x * 10 + j
if low <= x <= high:
ans.append(x)
return sorted(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) in practice since the total sequential numbers are limited by digit count (1-9), even with high up to 10^9. Space complexity is O(1) extra beyond the output list, as numbers are generated on the fly and stored only if they fall in range. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focuses on generating numbers without testing every integer individually.
- question_mark
Expects you to recognize the sequential digit pattern quickly.
- question_mark
Checks for efficiency by restricting generation to relevant digit lengths.
常见陷阱
外企场景- error
Attempting to iterate every integer from low to high, which is inefficient.
- error
Forgetting to handle different digit lengths separately, leading to missed numbers.
- error
Not maintaining ascending order, causing additional unnecessary sorting.
进阶变体
外企场景- arrow_right_alt
Return sequential digits in descending order instead of ascending.
- arrow_right_alt
Count the number of sequential digit numbers within a range instead of listing them.
- arrow_right_alt
Find the next sequential digit number greater than a given value.