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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- Write a program to find the nthsuper ugly number. Super u...
- Write a program to find the nth super ugly number. Super ...
- 欢迎访问我的博客:http://www.fupinyou.com 问题描述: Write a program to...
- Ugly Number II Write a program to find the n-th ugly numb...