美文网首页
313. Super Ugly Number

313. Super Ugly Number

作者: 阿团相信梦想都能实现 | 来源:发表于2016-09-21 04:47 被阅读0次
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