share my python codes in heapq


  • 0
    C
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    import heapq
    
    class Solution(object):
        def mergeKLists(self, lists):
            """
            :type lists: List[ListNode]
            :rtype: ListNode
            """
            heap = []
            for node in lists:
                if node:
                    heapq.heappush(heap, (node.val, node) )
            p = head = ListNode(-1)
            while heap:
                p.next = p = heapq.heappop(heap)[1]
                if p.next:
                    heapq.heappush( heap, (p.next.val, p.next) )  
    
            return head.next
    

Log in to reply
 

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