【Leetcode_总结】967. 连续差相同的数字 - python

Q :

返回所有长度为 N 且满足其每两个连续位上的数字之间的差的绝对值为 K 的非负整数

请注意,除了数字 0 本身之外,答案中的每个数字都不能有前导零。例如,01 因为有一个前导零,所以是无效的;但 0 是有效的。

你可以按任何顺序返回答案。

 

示例 1:

输入:N = 3, K = 7
输出:[181,292,707,818,929]
解释:注意,070 不是一个有效的数字,因为它有前导零。

示例 2:

输入:N = 2, K = 1
输出:[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

链接:https://leetcode-cn.com/problems/numbers-with-same-consecutive-differences/

思路:主要就是一个遍历的过程,对于每次一遍历的末位,分别加K或者-K,判断是否大于0,记录下来,思路很傻,效率不好,效率不好的原因主要是由于各种int转str 这个很消耗时间

代码:

class Solution:
    def numsSameConsecDiff(self, N, K):
        """
        :type N: int
        :type K: int
        :rtype: List[int]
        """
        if N == 0:
            return []
        if N == 1:
            return [i for i in range(10)]
        res = [str(i) for i in range(1, 10)]
        while N > 1:
            r1 = []
            r2 = []
            for i in range(len(res[:])):
                temp1 = int(res[i][-1]) - K
                temp2 = int(res[i][-1]) + K
                if temp1 < 10 and temp1 >= 0:
                    r1.append(res[i] + str(temp1))
                if temp2 < 10 and temp2 >= 0:
                    r2.append(res[i] + str(temp2))
            res = []
            res += r1
            res += r2
            N -= 1
        res_ = [int(r) for r in res]
        return list(set(res_))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值