【剑指Offer_14】丑数☆

题目描述

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

解题思路

起始数字为 1 1 ,因为丑数的所有质因子只能为 2 3 5 2、3、5 ,所以从 1 1 开始,每次乘上这三个数,找到最小的作为下一个丑数,并移动相应的指针。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index <= 1:
            return index
        index_2, index_3, index_5 = (0, 0, 0)
        res = [1]
        while len(res) < index:
            Min = min(res[index_2]*2, res[index_3]*3, res[index_5]*5)
            if Min == res[index_2]*2:
                index_2 += 1
            if Min == res[index_3]*3:
                index_3 += 1
            if Min == res[index_5]*5:
                index_5 += 1
            res.append(Min)
            if len(res) == index:
                return Min

猜你喜欢

转载自blog.csdn.net/Vici__/article/details/104527914