丑数
如果一个数的因数只有质因数3,5,7,那么这个数是丑数。特别的,1 也是丑数。前10个丑数是1,2,3,4,5,6,8,9,10,12。求第n个丑数。
思路
最先想到的是枚举的方法,从1开始,一直判断每个数是不是丑数,找到第n个丑数,这个方法不可行的原因是效率太低,第一,每次判断需要时间,第二,越到后面丑数越来越少,要遍历很多个数才能得到一个丑数。
换个思路,直接生成丑数,生成的第n个就是答案。
观察到丑数的规律,如果i是丑数,i*2,i*3,i*5也是丑数。
用最小堆。
每次从堆中取出最小的丑数,将其分别乘以2,3,5,得到新的3个丑数,如果从来没进过堆中,就进堆并标记,这样操作到第n次就得到第n个丑数。
代码
import heapq
class Solution:
"""
@param n: An integer
@return: return a integer as description.
"""
def nth_ugly_number(self, n: int) -> int:
# write your code here
heap = []
heapq.heappush(heap, 1)
seen = set()
seen.add(1)
factors = [2,3,5]
cur_ugly = 1
for _ in range(n):
cur_ugly = heapq.heappop(heap)
for f in factors:
new_ugly = cur_ugly*f
if new_ugly not in seen:
seen.add(new_ugly)
heapq.heappush(heap, new_ugly)
return cur_ugly
python自带heapq这个库,代表最小堆。