Merge k sorted linked lists and return it as one sorted list.
每个列表都已经是有序的 所以本质上是对有k个元素的数组进行排序(且数组内的元素需要变化
heapq 为python的一个实现最小堆的库
# T(nlogn) S(n)
import heapq
class Solution:
def mergeKLists(self, lists):
heap = []
for l in lists:
while l:
heapq.heappush(heap, l.val)
l = l.next
head = ListNode(val=None)
cur = head
while len(heap) != 0:
cur.next = ListNode(heapq.heappop(heap))
cur = cur.next
return head.next