[LeetCode] 970. Powerful Integers

Given three integers xy, and bound, return a list of all the powerful integers that have a value less than or equal to bound.

An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.

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 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32

Example 2:

Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]

Constraints:

  • 1 <= x, y <= 100
  • 0 <= bound <= 106

强整数。

给定三个整数 x 、 y 和 bound ,返回 值小于或等于 bound 的所有 强整数 组成的列表 。

如果某一整数可以表示为 x^i + y^j ,其中整数 i >= 0 且 j >= 0,那么我们认为该整数是一个 强整数 。

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/powerful-integers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题不涉及任何数学定理,暴力解找答案即可。题意是让我们找出 x^m + y^n <= bound 所有的解,那么我们就从 1 开始,用 for 循环一直试探看看有多少解是 <= bound 的。注意因为 1 的任意次方都是 1,所以如果 x 或者 y 是 1 的话,只需要计算一次。

注意题目给的数据范围,因为 bound <= 10^6,这个范围介于 2^19 - 2^20 之间,所以常数次计算就能得到所有答案,所以时间空间复杂度是 O(1)。

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public List<Integer> powerfulIntegers(int x, int y, int bound) {
 3         Set<Integer> set = new HashSet<>();
 4         for (int a = 1; a <= bound; a *= x) {
 5             for (int b = 1; a + b <= bound; b *= y) {
 6                 set.add(a + b);
 7                 // 1的任意次方都是1,所以计算一次即可
 8                 if (y == 1) {
 9                     break;
10                 }
11             }
12             if (x == 1) {
13                 break;
14             }
15         }
16         return new ArrayList<>(set);
17     }
18 }

 

LeetCode 题目总结

posted @ 2023-05-04 01:02  CNoodle  阅读(26)  评论(0)    收藏  举报