LeetCode 970. 强整数
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 970. 强整数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 暴力法
- 2.2 優化雙重循環
1. 題目
給定兩個正整數 x 和 y,如果某一整數等于 xi + yj,其中整數 i >= 0 且 j >= 0,那么我們認為該整數是一個強整數。
返回值小于或等于 bound 的所有強整數組成的列表。
你可以按任何順序返回答案。在你的回答中,每個值最多出現一次。
示例 1: 輸入:x = 2, y = 3, bound = 10 輸出:[2,3,4,5,7,9,10]解釋:
2 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/powerful-integers
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
2.1 暴力法
- 雙重循環+set去重
2.2 優化雙重循環
- 優化x或者y等于1時的情況,提前退出(1的任何次方等于1,只有一種選擇)
or
class Solution { public:vector<int> powerfulIntegers(int x, int y, int bound) {int i, j, res;unordered_set<int> s;int Maxi = (x != 1) ? log(bound)/log(x)+1 : 1;int Maxj = (y != 1) ? log(bound)/log(y)+1 : 1;for(i = 0; i < Maxi; i++){for(j = 0; j < Maxj; j++){res = pow(x,i)+pow(y,j);if(res <= bound)s.insert(res);}} return vector<int> (s.begin(),s.end());} };總結
以上是生活随笔為你收集整理的LeetCode 970. 强整数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 211. 添加与搜索单
- 下一篇: 程序员面试金典 - 面试题 01.09.