剑指offer-33.丑数-Python

33.丑数

题目描述

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

记录

自己构建丑数数组,而不是从1-n的所有数中进行判断选择出丑数从而形成丑数数组。
前n个丑数组成的序列 = 由2,3,5组成的前n个数的序列

1
1,2
1,2,3
1,2,3,4

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index<=0:
            return 0
        res = [1]
        a = b = c = 0
        #生成丑数数组
        while(len(res) < index):
            nextMin = min(res[a] * 2,res[b] * 3,res[c] * 5)
            res.append(nextMin)
            while res[a] * 2 <= nextMin:
                a += 1
            while res[b] * 3 <= nextMin:
                b += 1
            while res[c] * 5 <= nextMin:
                c += 1
        return res[-1]

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