前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 970. 强整数

LeetCode 970. 强整数

作者头像
Michael阿明
发布2020-07-13 15:44:32
4260
发布2020-07-13 15:44:32
举报

1. 题目

给定两个正整数 x 和 y,如果某一整数等于 xi + yj,其中整数 i >= 0 且 j >= 0,那么我们认为该整数是一个强整数。

返回值小于或等于 bound 的所有强整数组成的列表。

你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。

代码语言:javascript
复制
示例 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

代码语言:javascript
复制
示例 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去重
代码语言:javascript
复制
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,只有一种选择)
代码语言:javascript
复制
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

代码语言:javascript
复制
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());
    }
};
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
    • 2.1 暴力法
      • 2.2 优化双重循环
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档