264. 丑数 II

264. 丑数 II

编写一个程序,找出第 n 个丑数。

丑数就是只包含质因数 2, 3, 5 的正整数。

示例:

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

 

思路:

因为下一个丑数必定 = min(之前某个丑数*2, 之前某个丑数*3, 之前某个丑数*5),也就是说我们需要定义三个索引,idx2,idx3,idx5,分别记录上一次正好满足条件的丑数位置。所以每次只需更新这三个索引,然后取最小值就好了。

 

代码:

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        if n<=0: return 0
        res = []
        res.append(1)
        index = 0
        idx2, idx3, idx5 = 0,0,0
        while(index<n):
            temp = min(res[idx2]*2, res[idx3]*3, res[idx5]*5)
            res.append(temp)
            while(res[idx2]*2<=res[-1]):
                idx2+=1
            while(res[idx3]*3<=res[-1]):
                idx3+=1
            while(res[idx5]*5<=res[-1]):
                idx5+=1
            index+=1
        return res[n-1]  

 

posted @ 2019-08-19 10:56  三年一梦  阅读(164)  评论(0)    收藏  举报