LeetCode-Python-1291. 顺次数(数学 + 打表)

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sequential-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

第一种思路:

长度为固定值 l 的顺次数是非常好找,

因为是顺次数,所以知道第一位数和长度,就可以知道整个数。

要找到固定长度的所有顺次数,就让首位从1开始往下找就可以了。

比如 长度为3的顺次数,就是123, 234, 345,以此类推。

时间复杂度:O(1)

空间复杂度:O(1),如果不计算结果数组的长度

class Solution(object):
    def sequentialDigits(self, low, high):
        """
        :type low: int
        :type high: int
        :rtype: 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

第二种思路:

因为顺次数的个数是有限的,所以完全可以利用打表来实现。

时间复杂度:O(1)

空间复杂度:O(1),如果不计算结果数组的长度

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
发布了734 篇原创文章 · 获赞 121 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/105216290