313. Super Ugly Number
use generator to save storage and speed up program
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
uglies=[1]
def gen(prime):
for ugly in uglies:
yield ugly*prime
#*unpack the list of generators
merged=heapq.merge(*map(gen,primes))
while len(uglies)<n:
#the first time next() is called, the gen() will be initialized and all elements of primes will run through the generator once and yield one ugly*prime each and pushed to the heap. the other times next() is called, it will return the next smallest element in the heap meanwhile yield one ugly*prime and push onto the heap
ugly=next(merged)
if ugly!=uglies[-1]:
uglies.append(ugly)
return uglies[-1]
本文标题:313. Super Ugly Number
本文链接:https://www.haomeiwen.com/subject/razoettx.html
网友评论