题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param lists ListNode类一维数组 # @return ListNode类 # class Solution: def mergeKLists(self , lists: List[ListNode]) -> ListNode: # write code here def check_min_index(lists_: list[ListNode]): # 返回链表列表中中的最小值的索引 return sorted(list(enumerate(lists_)), key=lambda _x: _x[1].val)[0][0] tmphead = node = ListNode(-1) # 去除 lists 中的空节点 newlists = [] for i in range(len(lists)): if lists[i] is not None: newlists.append(lists[i]) # 合并链表 while newlists: min_index = check_min_index(newlists) node.next = newlists[min_index] node = node.next newlists[min_index] = newlists[min_index].next if newlists[min_index] is None: newlists.remove(newlists[min_index]) return tmphead.next