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]

 

 

你可能感兴趣的:(LeetCode Python 第n个丑数)