Thursday, September 18, 2014

Leetcode: Merge k Sorted Lists @Python

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        heap = [(node.val, node) for node in lists if node]
        heapq.heapify(heap)
        curr=head = ListNode(0)
        while heap:
            curr.next= heapq.heappop(heap)[1]
            curr = curr.next
            if curr.next: heapq.heappush(heap, (curr.next.val, curr.next))
        return head.next

No comments :

Post a Comment