题意: 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, and n does not exceed 1690.
Hint:
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
思路:这题有很多做法,可以一个个的生成丑数,存在列表里,也可以利用一个heap的结构来存储,方法是这样的,仔细观察2,3,5三个数,2* 2<3* 2<3* 3<5* 2<5* 3<5* 5,利用堆每次pop都是最小数的原理,生成下一个大于堆内最大数的下一个丑数。
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
import heapq
heap, u = [], 0
heapq.heappush(heap,1)
for i in xrange(n):
u = heapq.heappop(heap)
if u%2==0:
heapq.heappush(heap,u*2)
elif u%3==0:
heapq.heappush(heap,u*2)
heapq.heappush(heap,u*3)
else:
heapq.heappush(heap,u*2)
heapq.heappush(heap,u*3)
heapq.heappush(heap,u*5)
return u
参考代码:
def nthUglyNumber2(self, n):
ugly = [1]
i2 = i3 = i5 = 0
while len(ugly) < n:
while ugly[i2] * 2 <= ugly[-1]: i2 += 1
while ugly[i3] * 3 <= ugly[-1]: i3 += 1
while ugly[i5] * 5 <= ugly[-1]: i5 += 1
ugly.append(min(ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5))
return ugly[-1]
def nthUglyNumber3(self, n):
q2, q3, q5 = [2], [3], [5]
ugly = 1
for u in heapq.merge(q2, q3, q5):
if n == 1:
return ugly
if u > ugly:
ugly = u
n -= 1
q2 += 2 * u,
q3 += 3 * u,
q5 += 5 * u,
return ugly