题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
# -*- coding:utf-8 -*-
#剑指offer上的解法,这是借鉴的,我自己写的时候,一直有一个错误,
#就是我添加的丑数会有重复的情况,比如2*3和3*2都是6,这个6在我的列表中就出现了两次。
#这个程序用while解决了该问题,使这个小于这个丑数的所有组合都不会发生
class Solution:
def GetUglyNumber_Solution(self, index):
if index < 1:
return 0
res = [1]
t2 = t3 = t5 = 0
nextIdx = 1
while nextIdx < index:
minNum = min(res[t2] * 2, res[t3] * 3, res[t5] * 5)
res.append(minNum)
while res[t2] * 2 <= minNum:
t2 += 1
while res[t3] * 3 <= minNum:
t3 += 1
while res[t5] * 5 <= minNum:
t5 += 1
nextIdx += 1
return res[nextIdx - 1]
并且,下面是python大佬的几种解决方法
1.
def GetUglyNumber_Solution(self, index):
res=[2**i*3**j*5**k for i in range(30) for j in range(20) for k in range(15)]
res.sort()
return res[index-1] if index else 0
def GetUglyNumber_Solution(self, index):
res=[2**i*3**j*5**k for i in range(30) for j in range(20) for k in range(15)]
return sorted(res)[index-1] if index else 0
return sorted([2**i*3**j*5**k for i in range(30) for j in range(20) for k in range(15)])[index-1] if index else 0