设置1,2,3,4,5;共5个丑数,下一次的丑数一定是质数因子2,3,5两两相乘的最小值,代码如下:
# -*- coding:utf-8 -*- class Solution: def GetUglyNumber_Solution(self, index): uglylist = [1,2,3,4,5] if index ==0: return 0 # res[0] = 1 i2 = 0 i3 = 0 i5 = 0 i=1 while len(uglylist) <= index+1: add = min(uglylist[i2]*2, uglylist[i3]*3, uglylist[i5]*5) if add == uglylist[i2]*2: i2 = i2+1 if add == uglylist[i3]*3: i3 = i3+1 if add == uglylist[i5]*5: i5 = i5+1 # print(uglylist) if add > uglylist[-1]: uglylist.append(add) return uglylist[index-1] # write code here