1. 程式人生 > >演算法分析課每週練習 Merge k Sorted Lists

演算法分析課每週練習 Merge k Sorted Lists

題目

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

分析

Merge Sort 裡有合併Sorted List的步驟,這個是一般情況,如果兩兩合併時間複雜度,O(Node* log (Lists)),但比較佔記憶體

這裡用一個PriorityQueue來解決插入順序,每次插入都要pop和enqueue,時間複雜度是O(1)和O(log(Lists)),總體時間複雜度為O(Node*log(Lists)),

空間複雜度是O(Node + Lists)

from Queue import PriorityQueue
class Solution(object):
    def mergeKLists(self, lists):
        dummy = ListNode(None)
        curr = dummy
        q = PriorityQueue()
        for node in lists:
            if node: q.put((node.val,node))
        while q.qsize()>0:
            curr.next = q.get()[1]
            curr=curr.next
            if curr.next: q.put((curr.next.val, curr.next))
        return dummy.next