LeetCode 题解工作台
强整数
给定三个整数 x 、 y 和 bound ,返回 值小于或等于 bound 的所有 强整数 组成的列表 。 如果某一整数可以表示为 x i + y j ,其中整数 i >= 0 且 j >= 0 ,那么我们认为该整数是一个 强整数 。 你可以按 任何顺序 返回答案。在你的回答中,每个值 最多 出现一…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 哈希·数学
答案摘要
根据题目描述,一个强整数可以表示成 $x^i + y^j$,其中 $i \geq 0$, $j \geq 0$。 题目需要我们找出所有不超过 的强整数,我们注意到 的取值范围不超过 ,而 $2^{20} = 1048576 \gt 10^6$。因此,如果 $x \geq 2$,那么 最大不超过 ,才有可能使得 $x^i + y^j \leq bound$ 成立。同理,如果 $y \geq 2…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·数学 题型思路
题目描述
给定三个整数 x 、 y 和 bound ,返回 值小于或等于 bound 的所有 强整数 组成的列表 。
如果某一整数可以表示为 xi + yj ,其中整数 i >= 0 且 j >= 0,那么我们认为该整数是一个 强整数 。
你可以按 任何顺序 返回答案。在你的回答中,每个值 最多 出现一次。
示例 1:
输入:x = 2, y = 3, bound = 10 输出:[2,3,4,5,7,9,10] 解释: 2 = 20 + 30 3 = 21 + 30 4 = 20 + 31 5 = 21 + 31 7 = 22 + 31 9 = 23 + 30 10 = 20 + 32
示例 2:
输入:x = 3, y = 5, bound = 15 输出:[2,4,6,8,10,14]
提示:
1 <= x, y <= 1000 <= bound <= 106
解题思路
方法一:哈希表 + 枚举
根据题目描述,一个强整数可以表示成 ,其中 , 。
题目需要我们找出所有不超过 的强整数,我们注意到 的取值范围不超过 ,而 。因此,如果 ,那么 最大不超过 ,才有可能使得 成立。同理,如果 ,那么 最大不超过 。
因此我们可以使用双重循环,枚举所有可能的 和 ,分别记为 和 ,并保证 ,此时 即为一个强整数。我们使用哈希表存储所有满足条件的强整数,最后将哈希表中的所有元素转换成答案列表返回即可。
注意,如果 或者 ,那么 或者 的值恒等于 ,对应的循环只需要执行一次即可退出。
时间复杂度 ,空间复杂度 。
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
ans = set()
a = 1
while a <= bound:
b = 1
while a + b <= bound:
ans.add(a + b)
b *= y
if y == 1:
break
if x == 1:
break
a *= x
return list(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log_bound(x) * log_bound(y)) because we iterate powers of x and y only until the bound is exceeded. Space complexity is O(N * M) where N and M are the number of powers of x and y that fit within the bound, required for storing sums in a Hash Set. |
| 空间 | O(N \times M) |
面试官常问的追问
外企场景- question_mark
Focus on pruning loops as soon as x^i + y^j exceeds the bound.
- question_mark
Ensure duplicate sums are not included, highlighting proper Hash Table usage.
- question_mark
Expect clarification on why enumeration combined with mathematical stopping conditions is efficient.
常见陷阱
外企场景- error
Failing to break loops early, leading to unnecessary computations and potential TLE.
- error
Using a list instead of a Hash Set, which can allow duplicates in the output.
- error
Incorrectly handling the edge case when x or y equals 1, which causes infinite loops if not properly stopped.
进阶变体
外企场景- arrow_right_alt
Return powerful integers in sorted order instead of arbitrary order.
- arrow_right_alt
Restrict i and j to a maximum exponent value instead of using bound.
- arrow_right_alt
Compute sums modulo a number to avoid large integers and test modular properties.