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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章