Leetcode 23.合并K个排序链表(Merge k Sorted Lists)

Leetcode 23.合并K个排序链表

1 题目描述(Leetcode题目链接)

  合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

2 题解

  以链表头结点值建立最小堆,一起合并。更多关于堆的内容。

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

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        while None in lists:
            lists.remove(None)

        Head = ListNode(0)
        heap_size = len(lists)

        def min_heapify(i, heap_size):
            l = 2*i + 1
            r = 2*i + 2
            if l < heap_size and lists[l].val < lists[i].val:
                smallests = l
            else:
                smallests = i
            if r < heap_size and lists[r].val < lists[smallests].val:
                smallests = r
            if smallests != i:
                lists[i], lists[smallests] = lists[smallests], lists[i]
                min_heapify(smallests, heap_size)

        for i in range(heap_size//2 + 1, -1, -1):
            min_heapify(i, heap_size)
        
        p = Head
        while heap_size:
            p.next = lists[0]
            p = p.next
            lists[0] = lists[0].next
            if not lists[0]:
                lists[0] = lists[heap_size-1]
                heap_size -= 1
            min_heapify(0, heap_size)
                
        return Head.next

你可能感兴趣的:(Leetcode,leetcode,算法,链表)