剑指offer- python实现

面试题49:丑数

2020-03-27  本文已影响0人  不会编程的程序猿甲

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

思路:
以空间来换取时间效率,用一个辅助数组res来保存从小到大的丑数,为了只计算丑数,采取的策略为:假设已经有排好序的数,那么一定存在一个t2位置的元素乘以2大于当前的最大值,而之前的都小于当前的最大值,记录该位置,同理记录t3和t5的位置,下一个丑数就是者三个数中的最小数,依次计算直到需要计算的索引为止。

49 丑数.png

代码实现:

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        if index <= 0:
            return 0
        #初始化
        res = [1]         #第一个丑数是1
        nextindex = 1     #初始化下一个丑数的索引
        t2 = t3 = t5 = 0  #初始化索引

        #循环
        while nextindex < index:
            min_val = min(res[t2]*2,res[t3]*3,res[t5]*5)
            res.append(min_val)
            #计算下一个大于当前min_val的t2*2
            while res[t2]*2 <= min_val:
                t2+=1
            #计算下一个大于当前min_val的t3*3
            while res[t3]*3 <= min_val:
                t3+=1
            #计算下一个大于当前min_val的t2*2          
            while res[t5]*5 <= min_val:
                t5+=1
            nextindex +=1    #索引更新
        #返回
        return res[nextindex-1]

提交结果:

上一篇 下一篇

猜你喜欢

热点阅读