给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
解题思路
分治加两个链表合并,或者用根堆,根堆的初始化方法很值得背诵,还涉及lambda的用法
AC代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
ListNode.__lt__ = lambda a, b: a.val < b.val
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
h = [head for head in lists if head]
dummyhead = ListNode()
indexhead = dummyhead
heapify(h)
while h:
node = heappop(h)
if node.next:
heappush(h, node.next)
indexhead.next = node
indexhead = indexhead.next
return dummyhead.next