263-264. Ugly Number I & II [Easy & Medium] 丑数系列

本文介绍了如何判断一个数是否为丑数(仅由2、3、5的倍数构成),并提供了一种求解第n个丑数的高效算法。通过Python实现,详细解析了算法思路与代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

263. Ugly Number

17368230-fd8d646f39e16028.PNG
263. Ugly Number

判断一个数是不是因数只有2,3,5。很简单的啦~

代码如下:

class Solution(object):
    def isUgly(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0:
            return False
        while num % 2 == 0:
            num /= 2
        while num % 3 == 0:
            num /= 3
        while num % 5 == 0:
            num /= 5
        return num == 1

264. Ugly Number II

17368230-d263a53e36488e28.PNG
264. Ugly Number II

下一个数字必然是之前的某个数字乘2、乘3、乘5得到的。
用index2,index3,index5分别记录乘2、乘3、乘5后能大于最后一个数的最小数的位置。
时间复杂度O(n)

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        myList = [1]
        index2 = index3 = index5 = 0
        while n - 1 > 0:
            n -= 1
            temp = min(myList[index2] * 2, myList[index3] * 3, myList[index5] * 5)
            myList.append(temp)
            if temp == myList[index2] * 2:
                index2 += 1
            if temp == myList[index3] * 3:
                index3 += 1
            if temp == myList[index5] * 5:
                index5 += 1
        return myList[-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值