leetcode 970. 强整数

【题目】970. 强整数

给定两个正整数 x 和 y,如果某一整数等于 x^i + y^j,其中整数 i >= 0 且 j >= 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

【解题思路1】暴力法

0≤i,j≤log x (bound)<18

class Solution {
    public List<Integer> powerfulIntegers(int x, int y, int bound) {
        int iMax = x == 1 ? 0 : (int)(Math.log(bound-1) / Math.log(x));
        int jMax = y == 1 ? 0 : (int)(Math.log(bound-1) / Math.log(y));
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i <= iMax; i++) {
            for (int j = 0; j <= jMax; j++) {
                if (Math.pow(x,i) + Math.pow(y,j) <= bound) {
                    set.add((int)(Math.pow(x,i) + Math.pow(y,j)));
                } else break;
            }
        }
        return new ArrayList<>(set);
    }
}

官方题解的范围是有问题的
2^19 < 10^6 < 2^20
x, y同时最小的话我们假设二者都是 2 (二者都为 1 的话该题就很难有答案了)我们不难发现 2 的20次方的值才超出了题目给出bound的最大范围( 2 的 18 次方是小于 10 的 7 次方的), 2 的 2 0次方是 7 位数( 10 的 7 次方),因此循环的时候需将range后面的参数调整为20就可以通过了

class Solution { 
    public List<Integer> powerfulIntegers(int x, int y, int bound) {
        Set<Integer> seen = new HashSet();
        for (int i = 0; i < 20 && Math.pow(x, i) <= bound; ++i)
            for (int j = 0; j < 20 && Math.pow(y, j) <= bound; ++j) {
                int v = (int) Math.pow(x, i) + (int) Math.pow(y, j);
                if (v <= bound)
                    seen.add(v);
            }

        return new ArrayList(seen);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章