Python Min Heap


  • 1
    class Solution(object):
        def mergeKLists(self, lists):
            ans = []
            heap = []
            for i in xrange(len(lists)):
                if lists[i]:
                    heapq.heappush(heap, (lists[i].val, lists[i]))
            while heap:
                top = heapq.heappop(heap)
                ans.append(top[0])
                if top[1].next:
                    heapq.heappush(heap, (top[1].next.val, top[1].next))
            return ans
    

  • 0
    F

    @Ipeq1 very clever and efficient. Only question is, you are returning a python list type, rather a sorted linked list. Personally I think it's fine. but wonder if this could pass the test.


Log in to reply
 

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