A Trivial Python Solution (With heapq ....)


  • 0
    X

    A trivial solution using python. Good to gain an abstract.

    class Solution(object):
        def mergeKLists(self, lists):
            """
            :type lists: List[ListNode]
            :rtype: ListNode
            """
            from heapq import heapify, heappop, heappush
            h = [(l.val, l) for l in lists if l]
            heapify(h)
            new_head = current = None
            while len(h):
                val, node = heappop(h)
                if node.next:
                    heappush(h, (node.next.val, node.next))
                if not new_head:
                    current = new_head = node
                else:
                    current.next = node
                    current = node
                    node.next = None
            return new_head

Log in to reply
 

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