23. Merge k Sorted Lists python leetcode 2016 new Season

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.


use priority queue will take O(n) time cause get max from priority will only take O(1)


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

from Queue import PriorityQueue
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        dummyHead = ListNode(None)
        currentNode = dummyHead
        queue = PriorityQueue()
        for list_ in lists:
            if list_:
                queue.put((list_.val, list_))
        while queue.qsize():
             node = queue.get()[1]
             currentNode.next = node
             currentNode = currentNode.next
             if node.next:
                 queue.put((node.next.val, node.next))
        return dummyHead.next


你可能感兴趣的:(23. Merge k Sorted Lists python leetcode 2016 new Season)