LeetCode Python 第n个丑数

挨个找的方法, 效率比较低

def findKthUgly(k):
    count = 0
    n = 1
    while True:
        if isUgly(n):
            count += 1
        if count == k:
            return n
        else:
            n += 1


def isUgly(number):
    while number%2 == 0:
        number = number/2
    while number%3 == 0:
        number = number/3
    while number%5 == 0:
        number == number/5
    if number == 1:
        return True
    else:
        return False

另外一种算法是从丑数出发*2,*3,*5计算后面的丑数,每次竞争上岗,将最小的值加入丑数列表,只是需要想办法找到比当前list中最大丑数大的第一个丑数,利用index2,index3,index5来维护每个数*2,*3,*5加入list,如果ugly[index2]*2加入list就将index2指向下一个丑数,以此类推。

def findKthUgly(k):
    ugly = []
    ugly.append(1)
    index = 1
    index2 = 0
    index3 = 0
    index5 = 0
    while index < k:
        val = min(ugly[index2]*2, ugly[index3]*3, ugly[index5]*5)
        if ugly[index2]*2 == val:
            index2 += 1
        if ugly[index3]*3 == val:
            index3 += 1
        if ugly[index5]*5 == val:
            index5 += 1
        ugly.append(val)
        index += 1
    return ugly[-1]

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值