力扣笔记(每日随机一题)—— 打强整数

问题(中等)

给定三个整数xybound ,返回 值小于或等于 bound 的所有 强整数 组成的列表 。

如果某一整数可以表示为 x i + y j x^i + y^j xi+yj ,其中整数 i > = 0 且 j > = 0 i >= 0 且 j >= 0 i>=0j>=0,那么我们认为该整数是一个 强整数

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/powerful-integers/

示例 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 , y < = 100 1 <= x, y <= 100 1<=x,y<=100
0 < = b o u n d < = 1 0 6 0 <= bound <= 10^6 0<=bound<=106

解题

思路

  1. 利用两个列表存储x,y的幂数据;
  2. 然后两组数据依次相加;
  3. 转为set()去除重复数据;

代码实现

class Solution(object):
    def powerfulIntegers(self, x, y, bound):
        """
        :type x: int
        :type y: int
        :type bound: int
        :rtype: List[int]
        """

        lx,ly = [1],[1]
        temp = []
        while lx[-1]<bound or ly[-1]<bound :
            lx.append(x*lx[-1])
            ly.append(y*ly[-1])    
        while lx[-1]>bound:
            lx.pop()
        while ly[-1]>bound:
            ly.pop()

        temp = list(set([lx[i]+ly[j] for i in range(len(lx)) for j in range(len(ly))]))
        while temp[-1]>bound:
            temp.pop()

        return temp

超出内存限制,继续调整;

当x>1时,因为bound的上限是10^6,因此i的上限为 20。
利用两层循环去掉存储两组幂数组,直接以单变量n表示 x i + y j x^i + y^j xi+yj

class Solution(object):
    def powerfulIntegers(self, x, y, bound):
        """
        :type x: int
        :type y: int
        :type bound: int
        :rtype: List[int]
        """

        lx,ly = [1],[1]
        temp = []
        for i in range(21):
            for j in range(21):
                n = x**i+y**j
                if n <= bound:
                    temp.append(n)

        temp = list(set(temp))

        return temp

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ACxz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值