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.