# -*- coding:utf-8 -*- class Solution: def GetUglyNumber_Solution(self, index): # write code here if index < 1 : return 0 """ # 思路1:先判断是否为丑数,是丑数的基础上count++ 直到count=index # 此思路时间复杂度过高,导致内存爆掉 def isUglyNumber(num): while num%2 == 0: num = num//2 while num%3 == 0: num = num//3 while num%5 == 0: num = num//5 if num == 1: return True else: return False count = 0 num = 1 while True: if isUglyNumber(num): count += 1 if count == index: return num num += 1 """ # 思路2:我们以上的思路,其实把丑数和不是丑数都进行了计算,时间复杂度很大; # 我们可以用空间来换时间,也就是将所有丑数存在一个list中 # 举例:[1,2,3,4,5,6,8,9,12]这是我们的前几个丑数,需要观察规律, # 我们可以发现后面的丑数其实是前面丑数*2或者3或者5得到的 uglylist = [1] t1,t2,t3 = 0,0,0 count = 1 while count != index: minval = min(2*uglylist[t1],3*uglylist[t2],5*uglylist[t3]) uglylist.append(minval) if minval == 2*uglylist[t1]: t1 += 1 if minval == 3*uglylist[t2]: t2 += 1 if minval == 5*uglylist[t3]: t3 += 1 count += 1 return uglylist[count-1]
原文:https://www.cnblogs.com/ivyharding/p/11338696.html