美文网首页
[Hard heap] 23. Merge k Sorted L

[Hard heap] 23. Merge k Sorted L

作者: Mree111 | 来源:发表于2019-10-23 11:46 被阅读0次

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

相关文章

网友评论

      本文标题:[Hard heap] 23. Merge k Sorted L

      本文链接:https://www.haomeiwen.com/subject/jhvhvctx.html