How does heapq.merge()
sort a list even without generate the list?
Not sure if I stated clear.
So, this is raised from the
Super Ugly Number problem at leetcode.
And this python code
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
merged = heapq.merge(*map(gen, primes))
while len(uglies) < n:
ugly = next(merged)
if ugly != uglies[-1]:
uglies.append(ugly)
return uglies[-1]
gave me a hard time understanding it. After I searched the concepts of "yield" and "heapq", I still don't get that in the while
loop, how merged
know that ugly in uglies>n
will not be smaller than uglies[n-1]
.