日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 970. 强整数

發布時間:2024/7/5 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

示例 2: 輸入:x = 3, y = 5, bound = 15 輸出:[2,4,6,8,10,14]提示: 1 <= x <= 100 1 <= y <= 100 0 <= bound <= 10^6

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/powerful-integers
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

2.1 暴力法

  • 雙重循環+set去重
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 : bound/2;int Maxj = (y != 1) ? log(bound)/log(y)+1 : bound/2;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());} };

2.2 優化雙重循環

  • 優化x或者y等于1時的情況,提前退出(1的任何次方等于1,只有一種選擇)
class Solution { public:vector<int> powerfulIntegers(int x, int y, int bound) {int i = 0, j = 0, res;unordered_set<int> s;int powx, powy;for(i = 0; (powx = pow(x,i)) <= bound; i++){for(j = 0; (powy = pow(y,j)) <= bound; j++){res = powx+powy;if(res <= bound)s.insert(res);if(y == 1)break;}if(x == 1)break;} return vector<int> (s.begin(),s.end());} };

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. 强整数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。