问题:把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

思路:按顺序把每个丑数放在数组中,求下一个丑数
下一个丑数必定由有数组中的某一个丑数A * 2, B * 3, C * 5 的中的最小值得来。
分析:在数组中必定有一个丑数M2, 在它之前的数 * 2 都小于当前最大丑数, 在它之后的数 * 2都大于当前最大丑数, 同样有M3, M5
其实每次我们只用比较3个数:用于乘2的最小的数、用于乘3的最小的数,用于乘5的最小的
数。也就是比较(2*x , 3*y, 5*z) ,x>=y>=z的
 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def GetUglyNumber_Solution(self, index):
 4         # write code here
 5         if index < 1:
 6             return 0
 7         count = 0
 8         result = [1]
 9         indexTwo , indexThree, indexFive = 0,0,0
10         
11     
12         while count < index-1:
13             newNum = min(result[indexTwo]*2, result[indexThree]*3, result[indexFive]*5)
14             result.append(newNum)
15             if newNum % 2 == 0:
16                 indexTwo += 1
17             if newNum % 3 == 0:
18                 indexThree += 1
19             if newNum % 5 == 0:
20                 indexFive += 1 
21             count += 1
22         return result[-1]

 

posted on 2017-08-03 15:15  刀刀121  阅读(88)  评论(0编辑  收藏  举报