這是悅樂書的第367次更新,第395篇原創
java
今天介紹的是LeetCode
算法題中Easy
級別的第229
題(順位題號是970
)。給定兩個正整數x
和y
,若是對於某些整數i >= 0
且j >= 0
等於x^i + y^j
,則整數是強大的。算法
返回值小於或等於bound
的全部強大整數的列表。數據結構
你能夠按任何順序返回答案。在你的答案中,每一個值最多應出現一次。例如:翻譯
輸入: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^2code
輸入:x = 3,y = 5,bound = 15
輸出:[2,4,6,8,10,14]class
注意:數據結構與算法
1 <= x <= 100List
1 <= y <= 100循環
0 <= bound <= 10^6
技巧
直接翻譯題目便可,沒有什麼特殊的技巧,可是須要注意一點,由於判斷條件時x或者y的幾回方小於bound
,若是x
或者y
爲1的時候,1的任何次方都會是1,會一直小於bound
,會形成死循環。
public List<Integer> powerfulIntegers(int x, int y, int bound) { Set<Integer> set = new HashSet<Integer>(); for (int i=0; Math.pow(x, i) < bound; i++) { for (int j=0; Math.pow(y, j) < bound; j++) { int sum = (int)Math.pow(x, i)+(int)Math.pow(y, j); if (sum <= bound) { set.add((int)sum); } // y等於1時,容易形成死循環,要結束掉 if (y == 1) { break; } } // x等於1時,容易形成死循環,要結束掉 if (x == 1) { break; } } return new ArrayList<>(set); }
針對上面第一種解法,咱們也能夠不借助Math
類的pow
方法,用累計相乘替代,思路都是同樣的。
public List<Integer> powerfulIntegers2(int x, int y, int bound) { Set<Integer> set = new HashSet<Integer>(); for (int i=1; i<bound; i *= x) { for (int j=1; j<bound; j *= y) { if (i+j <= bound) { set.add(i+j); } if (y == 1) { break; } } if (x == 1) { break; } } return new ArrayList<>(set); }
算法專題目前已連續日更超過七個月,算法題文章235+篇,公衆號對話框回覆【數據結構與算法】、【算法】、【數據結構】中的任一關鍵詞,獲取系列文章合集。
以上就是所有內容,若是你們有什麼好的解法思路、建議或者其餘問題,能夠下方留言交流,點贊、留言、轉發就是對我最大的回報和支持!