题目
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
举例
先举例最小的10个丑数:1,2,3,4,5,6,8,9,10,12。
中间7和11不是丑数,因为他们的因子中有7和11本身。
思路
首先,p是一个丑数,那么2*p和3*p和5*p肯定也是丑数。
接着,假设 [a,b,c] 是三个相连接的丑数。那么我们先比较 2*a 和3*a和5*a,然后得到最小的丑数d。则列表为[a,b,c,d] 。然后我们就可以比较2*b和3*a和5*a,假设是2*b最小,然后得到最小值e。则列表为[a,b,c,d,e]。然后比较2*c和3*a和5*a这样一直进行下去,直到得到指定的位置的丑数。
代码 version-1
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
array = [1]
if index<=0:
return 0
elif index==1:
return 1
else:
index_two = 0
index_three = 0
index_five = 0
i = 1
while i<index:
array.append(min(array[index_two]*2,array[index_three]*3,array[index_five]*5))
if array[-1]==array[index_two]*2:
index_two = index_two+1
if array[-1]==array[index_three]*3:
index_three = index_three+1
if array[-1]==array[index_five]*5:
index_five = index_five+1
i = i+1
print array
return array[-1]
分析
代码时没有问题的,但是这份代码的需要非常大的空间,如果index是一个非常大的数,那么,array就是一个非常大的list。所以这份代码是可以进行优化的。
代码 version-2
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
array = [1]
if index<=0:
return 0
elif index==1:
return 1
else:
index_two = 0
index_three = 0
index_five = 0
i = 1
while i<index:
array.append(min(array[index_two]*2,array[index_three]*3,array[index_five]*5))
if array[-1]==array[index_two]*2:
index_two = index_two+1
if array[-1]==array[index_three]*3:
index_three = index_three+1
if array[-1]==array[index_five]*5:
index_five = index_five+1
i = i+1
while index_two!=0 and index_three!=0 and index_five!=0:
index_two = index_two-1
index_three = index_three-1
index_five = index_five-1
del array[0]
# print array
return array[-1]
最后加了一个根据2,3,5的位置来删除array中元素的while循环。
虽然个人觉得这样似乎可以减少一定的空间复杂度,但事实上似乎不是的,因为提交之后,version-2所需要的内存空间却大于version-1的。有点迷。
以上仅是个人观点,如有错误,欢迎指正