python heapq solution


  • 0
    M
    # 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
            """
            lheap = []
            for list in lists:
                if list: heapq.heappush(lheap,(list.val,list))
            dummy = ListNode(None)
            cur = dummy
            while lheap:
                node = heapq.heappop(lheap)[-1]
                cur.next = node
                cur = cur.next
                if node.next:
                    heapq.heappush(lheap,(node.next.val,node.next))
            return dummy.next

Log in to reply
 

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