You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: []
Constraints:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
is sorted in ascending order.- The sum of
lists[i].length
won't exceed10^4
.
这题是LeetCode 21. Merge Two Sorted Lists 的拓展,要求合并的不再是两个而是k个有序链表。其实解题思路是一样的,用k个指针分别指向k个有序链表的头节点,然后从k个指针指向的当前节点值中找到值最小的节点,该节点就是所有节点中最小的那个,因此可以被取出放入结果中。这种解法的一个关键问题是如何快速地从K个节点中找到值最小的那个?优先级队列(priority queue)或叫最小堆(min heap)可以被用来解决这个问题。如果我们把k个节点放入优先级队列中,那么它的顶部永远是值最小的那个。这样我们就可以每次从优先级队列中弹出值最小的那个节点,把该节点放入结果中,然后再把该节点的下一个节点(如不为空的话)再压入优先级队列中。一直循环直到队列为空为止。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class MyNode:
def __init__(self, node):
self.node = node
def __lt__(self, other):
return self.node.val < other.node.val
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
pq = []
for list in lists:
if list:
heapq.heappush(pq, MyNode(list))
preHead = ListNode(0)
cur = preHead
while pq:
node = heapq.heappop(pq).node
if node.next:
heapq.heappush(pq, MyNode(node.next))
node.next = None
cur.next = node
cur = cur.next
return preHead.next