LeetCode 题解工作台

顺次数

我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。 请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。 示例 1: 输出: low = 100, high = 300 输出: [123,234] 示例 2: 输出: low = 1000, h…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · Enumeration-driven solution strategy

bolt

答案摘要

我们可以枚举数字的第一位 ,然后枚举数字的最后一位 ,那么这个数字就是 这 个数字组成的。我们可以通过不断地将数字乘以 并加上下一个数字 来得到下一个数字,如果数字在 $[low, high]$ 的范围内,我们就将它加入答案中。 枚举结束后,我们将答案数组排序并返回即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Enumeration-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 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
lightbulb

解题思路

方法一:枚举

我们可以枚举数字的第一位 ii,然后枚举数字的最后一位 jj,那么这个数字就是 i,i+1,,ji,i+1,\cdots,jji+1j-i+1 个数字组成的。我们可以通过不断地将数字乘以 1010 并加上下一个数字 j+1j+1 来得到下一个数字,如果数字在 [low,high][low, high] 的范围内,我们就将它加入答案中。

枚举结束后,我们将答案数组排序并返回即可。

时间复杂度近似 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
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)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

顺次数题解:Enumeration-driven solu… | LeetCode #1291 中等