劍指offer-醜數 python

題目描述

把只包含質因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因爲它包含質因子7。 習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。

 

class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index < 7:
            return index
        res = [0] * index
        res[0] = 1
        t2,t3,t5,i = 0,0,0,1
        while i < index:
            res[i] = min(res[t2]*2,min(res[t3]*3,res[t5]*5))
            if res[i] == res[t2]*2:
                t2 += 1
            if res[i] == res[t3]*3:
                t3 += 1
            if res[i] == res[t5]*5:
                t5 += 1
            i += 1
        return res[index-1]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章