PS:今天有点急于求成了,接连几天的简单题的ac让我迷失了自我,今天随即一题随机到了中等题,简单看了一下觉得可以做,没想到看上去简单做起来却是各种各样的问题。原来自己还是小白,还是得认识自我。
题目:
给定三个整数 x 、 y 和 bound ,返回 值小于或等于 bound 的所有 强整数 组成的列表 。
如果某一整数可以表示为 xi + yj ,其中整数 i >= 0 且 j >= 0,那么我们认为该整数是一个 强整数 。
你可以按 任何顺序 返回答案。在你的回答中,每个值 最多 出现一次。
示例 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]
先说一下自己的解题思路,我想设置两个嵌套for循环,分别为i和j;然后将得到的强整数与bound进行比较,不大于则输出。
class Solution {
public:
vector<int> powerfulIntegers(int x, int y, int bound)
{
int count=0,i,j;
{
for(i = 0;i <= 100; i++)
{
for(j = 0;j <= 100; j++)
{
count = x^i + y^j;
if (count <= bound) return count;
}
}
}
}
};
但是这个代码甚至都没有通过编译,提示我return语句那里出错了,初步确定是因为count值一直在变化,所以没有一个确定的值返回。
看一下高赞回答:
class Solution {
public:
vector<int> powerfulIntegers(int x, int y, int bound) {
unordered_set<int> s;
for(int i = 1; i < bound; i *= x){
for(int j = 1; j < bound; j *= y){
if(i + j <= bound) s.insert(i + j);
if(y == 1) break;
}
if(x == 1) break;
}
return {s.begin(), s.end()}; // 并没有要求顺序返回
}
};
很巧妙,学到了怎么通过return语句返回一个数组值,而且知道了怎么通过一个快速的插入来把值向数组里面插入。即s.insert(数值),返回则用return{s.begin(),s.end()};学到就是赚到。
此外 若是不讨论 x =1或者y=1的情况,会导致代码执行时间大大增加从而超出时间限制.