Python easy to come up solution with Priority Queue


  • 1
    from heapq import *
    
    class Solution(object):
        def nthUglyNumber(self, n):
            h = [1]
            i = 0
            s = set()
            while i < n:
                e = heappop(h)
                if e not in s:
                    s.add(e)
                    heappush(h, e*2)
                    heappush(h, e*3)
                    heappush(h, e*5)
                    i += 1
            return e
    

    Of course, not an optimized solution but it is something you can easily come up with and code fast during the interview.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.