Ugly Number II
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.
Hint:
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. Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
分析:
没看Hint之前,我以为可以用母函数来做,后来发现母函数之间的组合是加法,这里是乘法。之后又使用三层循环暴力组合2,3,5,结果一直超时。
代码1,使用最小堆:
class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ from heapq import heappop, heappush h2, h3, h5 = [2], [3], [5] min_num = 1 while n > 1: u2, u3, u5 = h2[0], h3[0], h5[0] min_num = min(u2, u3, u5) if min_num == u2: heappop(h2) heappush(h2, u2 * 2) heappush(h3, u2 * 3) heappush(h5, u2 * 5) if min_num == u3: heappop(h3) heappush(h3, u3 * 3) heappush(h5, u3 * 5) if min_num == u5: heappop(h5) heappush(h5, u5 * 5) n -= 1 return min_num
代码2:
class Solution(object): def nthUglyNumber(self, n): """ :type n: int :rtype: int """ uglylst = [1] i2, i3, i5 = 0, 0, 0 # represent the uglylst index while n > 1: u2, u3, u5 = uglylst[i2] * 2, uglylst[i3] * 3, uglylst[i5] * 5 min_num = min(u2, u3, u5) if min_num == u2: i2 += 1 if min_num == u3: i3 += 1 if min_num == u5: i5 += 1 uglylst.append(min_num) n -= 1 return uglylst[-1]