题解 | #合并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: lists = [node for node in lists if node is not None] if len(lists) == 0: return None res = ListNode(-1) # 添加个临时表头 cur = res while True: if len(lists) == 1: cur.next = lists[0] break tmp = [] for i in range(len(lists)): tmp.append(lists[i].val) min_value = min(tmp) min_index = tmp.index(min_value) cur.next = lists[min_index] cur = cur.next lists[min_index] = lists[min_index].next if lists[min_index] == None: del lists[min_index] return res.next