题目:Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
思路:跟生成斐波那鍥数列有些相似,假如当前序列是满足要求的丑数序列,那么将这个序列中的每个数字都分别乘以2、3、5,从中挑出超出序列的最小值即可。但是这么做会有大量的重复计算,比如一个数字再乘一个2可能都已经在序列中了,就没必要再计算了。这可以通过维护三个不同的指针完成,三个指针分别表示当前序列中乘2便超出序列的最大数字,乘3便超出序列的最大数字和乘5便超出序列的最大数字。下一个数字一定是这三个数字分别乘以2、3、5中的最小值。
代码:
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return -1
nums = [1]
last_2 = 0
last_3 = 0
last_5 = 0
while len(nums) < n:
next_ugly = min([nums[last_2]*2,nums[last_3]*3,nums[last_5]*5])
nums.append(next_ugly)
while nums[last_2]*2 <= next_ugly:
last_2 += 1
while nums[last_3]*3 <= next_ugly:
last_3 += 1
while nums[last_5]*5 <= next_ugly:
last_5 += 1
return nums[-1]