题目描述:
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
思路:
利用之前的数生下一个数。开三个tmp分别存有可能产生下一个数的变量。
代码:
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index == 0:
return 0
if index == 1:
return 1
elif index == 2:
return 2
elif index == 3:
return 3
elif index == 4:
return 4
else:
c_num = [1,2,3,4]
index_2 = 2
index_3 = 1
index_5 = 0
for i in range(5, index+1):
new_c = min(c_num[index_2]*2,c_num[index_3]*3,c_num[index_5]*5)
for j in range(index_2, i):
if c_num[j]*2 > new_c:
index_2 = j
break
for j in range(index_3, i):
if c_num[j]*3 > new_c:
index_3 = j
break
for j in range(index_5, i):
if c_num[j]*5 > new_c:
index_5 = j
break
c_num.append(new_c)
return c_num[-1]