描述
Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0.
Return a list of all powerful integers that have value less than or equal to bound.
You may return the answer in any order. In your answer, each value should occur at most once.
Example 1:
Input: x = 2, y = 3, bound = 10
Output: [2,3,4,5,7,9,10]
Explanation:
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
Example 2:
Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]
Note:
1 <= x <= 100 1 <= y <= 100 0 <= bound <= 10^6
解析
根据题意,只需要先找出只有 x 的时候,找出刚刚大于 bound 情况下的幂值 i ,然后在只有 y 的时候,找出刚刚大于 bound 情况下的幂值 j ,这里要注意防止 x/y 为 1 ,这种情况,直接给 i/j 设置为 0 即可。然后双重循环 i 和 j ,将计算出的每个结果存入 set 集合中即可得到结果。
解答
class Solution(object):
def powerfulIntegers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
r = set()
i = 0
if x>1:
while x ** i <= bound:
i += 1
j = 0
if y>1:
while y ** j <= bound:
j += 1
for k in range(i+1):
for m in range(j+1):
t = x ** k + y ** m
if t <= bound :
r.add(t)
else:
break
return list(r)
运行结果
Runtime: 12 ms, faster than 96.91% of Python online submissions for Powerful Integers.
Memory Usage: 13.4 MB, less than 73.20% of Python online submissions for Powerful Integers.
原题链接:leetcode.com/problems/po…
您的支持是我最大的动力