要求
我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。
请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。
示例 1:
输出:low = 100, high = 300
输出:[123,234]
示例 2:
输出:low = 1000, high = 13000
输出:[1234,2345,3456,4567,5678,6789,12345]
核心代码
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
res = []
l_low = len(str(low))
l_high = len(str(high))
for l in range(l_low,l_high + 1):
for start_digit in range(1,11 - l):
num = ""
for k in range(l):
num += str(start_digit + k)
num = int(num)
if low <= num <= high:
res.append(num)
return res
另一解法
class Solution(object):
def sequentialDigits(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
nums = [12, 23, 34, 45, 56, 67, 78, 89,
123, 234, 345, 456, 567, 678, 789,
1234, 2345, 3456,4567, 5678, 6789,
12345, 23456, 34567, 45678, 56789,
123456, 234567, 345678, 456789,
1234567, 2345678, 3456789,
12345678, 23456789,
123456789]
res = []
for num in nums:
if low <= num <= high:
res.append(num)
return res
解题思路:第一种解法:我们使用位置,假设low = 100,说明我们数字至少是三位起步,然后我们需要考虑位数,从for start_digit in range(1,11 - l),因为我们想要把数据拼接到位数到l,所以我们需要计算一下最小的数字是从1开始,到那个数字结束,后面拼接k位数字合适,然后从起始位开始循环l的长度,布不断对起始数字进行加,就是后位大前位1,比较巧妙的方法时间复杂度:O(1) 空间复杂度:O(1),如果不计算结果数组的长度;第二种解法:我们将所有是顺位数都提取出来,然后循环遍历在范围中的进行输出即可,比较好理解。时间复杂度:O(1)空间复杂度:O(1),如果不计算结果数组的长度