首页 > 其他 > 详细

【leetcode】1215.Stepping Numbers

时间:2019-10-07 09:04:06      阅读:127      评论:0      收藏:0      [点我收藏+]

题目如下:

Stepping Number is an integer such that all of its adjacent digits have an absolute difference of exactly 1. For example, 321 is a Stepping Number while 421 is not.

Given two integers low and high, find and return a sorted list of all the Stepping Numbers in the range [low, high] inclusive.

 

Example 1:

Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]

 

Constraints:

  • 0 <= low <= high <= 2 * 10^9

解题思路:如果x是一个Stepping Number,假设x的个位是y,那么x*10 + y - 1 (y-1 >=0) 和 x*10 + y + 1 (y+1<=9) 也是Stepping Number,根据这个规律把所有符合条件的数字求出来即可。

代码如下:

class Solution(object):
    def countSteppingNumbers(self, low, high):
        """
        :type low: int
        :type high: int
        :rtype: List[int]
        """
        queue = range(0,10)
        res = set()
        while len(queue) > 0:
            val = queue.pop(0)
            if val >= low and val <= high:
                res.add(val)
            last = int(str(val)[-1])
            if last < 9:
                new_val = int(str(val) + str(last+1))
                if new_val <= high:
                    queue.append(new_val)
            if last > 0:
                new_val = int(str(val) + str(last-1))
                if new_val <= high:
                    queue.append(new_val)
        return sorted(list(res))

 

【leetcode】1215.Stepping Numbers

原文:https://www.cnblogs.com/seyjs/p/11629278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!