1. 程式人生 > >23. 合併K個排序連結串列

23. 合併K個排序連結串列

合併 個排序連結串列,返回合併後的排序連結串列。請分析和描述演算法的複雜度。

示例:

輸入:
[
  1->4->5,
  1->3->4,
  2->6
]
輸出: 1->1->2->3->4->4->5->6
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        lists = [ele for ele in lists if ele]
        # 第一次調整堆
        for i in range(len(lists) // 2 - 1, -1, -1):
            self.adjust(i, lists)
        head = dummy = ListNode(0)
        while lists:
            head.next = lists[0]
            head = head.next
            lists[0] = lists[0].next
            if not lists[0]:
                lists[0] = lists[-1]
                lists = lists[:-1]
            self.adjust(0, lists)
        return dummy.next
            
    def adjust(self, i, lists):
        while 2 * i + 1 < len(lists):
            tmp = 2 * i + 1
            if tmp + 1 < len(lists) and lists[tmp].val > lists[tmp + 1].val:
                tmp += 1
            if lists[i].val <= lists[tmp].val:
                break
            lists[i], lists[tmp] = lists[tmp], lists[i]
            i = tmp