Merge K lists -- heapq, python


  • 0
    W
    class Solution(object):
    def mergeKLists(self, lists):
        h = []
        
        head = ListNode(0)
        root = head
        for node in lists:
            if node:
                heapq.heappush(h,(node.val,node))
        while h:
            item = heapq.heappop(h)
            root.next= item[1]
            if item[1].next:
                heapq.heappush(h,(item[1].next.val,item[1].next))
            root = root.next
        return head.next

Log in to reply
 

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