Leetcode 970:强整数(超详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/85932407

给定两个非负整数 xy,如果某一整数等于 x^i + y^j,其中整数 i >= 0j >= 0,那么我们认为该整数是一个强整数

返回值小于或等于 bound 的所有强整数组成的列表。

你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。

示例 1:

输入:x = 2, y = 3, bound = 10
输出:[2,3,4,5,7,9,10]
解释: 
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
7 = 2^2 + 3^1
9 = 2^3 + 3^0
10 = 2^0 + 3^2

示例 2:

输入:x = 3, y = 5, bound = 15
输出:[2,4,6,8,10,14] 

提示:

  • 1 <= x <= 100
  • 1 <= y <= 100
  • 0 <= bound <= 10^6

解题思路

这个问题非常简单。我们首先计算ij的最大值

  • i = i n t ( l o g x 100 ) + 1   i f   x 1   e l s e   1 i=int(log_x^{100})+1\ if \ x \neq1 \ else \ 1
  • i = i n t ( l o g y 100 ) + 1   i f   y 1   e l s e   1 i=int(log_y^{100})+1\ if \ y \neq1 \ else \ 1

然后问题就非常简单了,只要遍历range(i)range(j),然后判断结果是否满足条件即可。但是我们在计算的过程中会出现重复值,所以一个解决方法就是通过set存储,最后转化为list即可。

class Solution:
    def powerfulIntegers(self, x, y, bound):
        """
        :type x: int
        :type y: int
        :type bound: int
        :rtype: List[int]
        """
        i = 1 if x == 1 else int(math.log(bound, x)) + 1
        j = 1 if y == 1 else int(math.log(bound, y)) + 1
        res = set()

        for m in range(i):
            for n in range(j):
                tmp = x**m + y**n
                if tmp <= bound:
                    res.add(tmp)
                    
        return list(res)

当然这种做法对于python来说比较合适,但是如果我们没有log函数的话,就要对上面这个代码稍加修改。

class Solution:
    def powerfulIntegers(self, x, y, bound):
        """
        :type x: int
        :type y: int
        :type bound: int
        :rtype: List[int]
        """
        res = set()
        i = bound if x == 1 else x
        j = bound if y == 1 else y
        
        m = 1
        while m < bound:
            n = 1
            while n + m <= bound:
                res.add(n + m)
                n *= j
            m *= i
            
        return list(res)      

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/85932407