[Hard heap] 23. Merge k Sorted L

2019-10-23  本文已影响0人  Mree111

Description

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

Solution

O(Nlogk) where k is the number of linked lists

from Queue import PriorityQueue

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        head = point = ListNode(0)
        q = PriorityQueue()
        for l in lists:
            if l:
                q.put((l.val, l))
        while not q.empty():
            val, node = q.get()
            point.next = ListNode(val)
            point = point.next
            node = node.next
            if node:
                q.put((node.val, node))
        return head.next
上一篇 下一篇

猜你喜欢

热点阅读