@author: sdubrz
@date: 2020.04.13
題目難度: 簡單
考察內容: 散列
原題鏈接 https://leetcode-cn.com/problems/powerful-integers/
題目的著作權歸領釦網絡所有,商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題代碼轉載請聯繫 lwyz521604#163.com
給定兩個正整數 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
通過次數5,624 提交次數14,342
解法
這是一個典型的可以用 Hash 來解得題目。題目比較簡單,主要是用來熟悉 Hash 的數據結構。不過需要注意 x
和 y
爲1時的情況。下面是用Java實現的代碼,兩層大循環搞定。
class Solution {
public List<Integer> powerfulIntegers(int x, int y, int bound) {
List<Integer> list = new LinkedList<>();
HashSet<Integer> hash = new HashSet<>();
int number1 = 1;
int number2 = 1;
int number3 = number1 + number2;
while(number3<=bound) {
number2 = 1;
number3 = number1 + number2;
while(number3<=bound) {
hash.add(number3);
if(y==1) {
break;
}
number2 *= y;
number3 = number1 + number2;
}
if(x==1) {
break;
}
number1 *= x;
number3 = number1 + 1;
}
Iterator<Integer> iter = hash.iterator();
while(iter.hasNext()) {
list.add(iter.next());
}
return list;
}
}
在 LeetCode 系統中的提交結果如下
執行結果: 通過 顯示詳情
執行用時 : 1 ms, 在所有 Java 提交中擊敗了 100.00% 的用戶
內存消耗 : 37.4 MB, 在所有 Java 提交中擊敗了 16.67% 的用戶