您的位置:首页 > 编程语言 > Python开发

LeetCode----Ugly NumberII

2015-09-30 10:05 495 查看
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:
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).

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息