这个题目可以使用最小堆去做,python的最小堆包:import heapq. heapq的详细介绍见博客
首先,先讲所有链表的头节点放入堆中,然后while 堆内还有节点时,把堆顶的最小元素pop出来,append到ans后面,指针后移,把新的元素push到堆中。
代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
import heapq
n = len(lists)
ans = ListNode()
curr = ans
heap = []
for i in range(n):
if lists[i]:
heapq.heappush(heap, (lists[i].val, i))
lists[i] = lists[i].next
while heap:
val, index = heapq.heappop(heap)
curr.next = ListNode(val=val)
curr = curr.next
if lists[index]:
heapq.heappush(heap, (lists[index].val, index))
lists[index] = lists[index].next
return ans.next