剑指offer-丑数(python)

2,3,5各自创建一个index,算出最小的append进入列表,然后对应的index增加一个,最后得到一个从小到大的丑数列表。

要注意range(index-1),因为一开始1这个丑数已经在里面了,最后只要输出最后一个丑数就行

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if not index:
            return 0
        res=[1]
        two_index=0
        three_index=0
        five_index=0
        for i in range(index-1):
            min_val=min(res[two_index]*2,res[three_index]*3,res[five_index]*5)
            res.append(min_val)
            if min_val%2==0:
                two_index+=1
            if min_val%3==0:
                three_index+=1
            if min_val%5==0:
                five_index+=1
        return res[-1]

你可能感兴趣的:(剑指offer)