zoukankan      html  css  js  c++  java
  • 【leetcode】1215.Stepping Numbers

    题目如下:

    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))
  • 相关阅读:
    圣杯布局(定宽与自适应)
    【转载】jQuery插件开发精品教程,让你的jQuery提升一个台阶
    DOM 事件深入浅出(一)
    匿名类型
    类和结构
    C#预处理器指令
    Main()方法
    枚举
    预定义数据类型
    C#语言
  • 原文地址:https://www.cnblogs.com/seyjs/p/11629278.html
Copyright © 2011-2022 走看看