题解 | #合并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类 # from typing import Optional class Solution: def mergeKLists(self , lists: List[ListNode]) -> ListNode: # write code here m = len(lists) if m == 0: return None if m == 1: return lists[0] left = self.mergeKLists(lists[: m // 2]) right = self.mergeKLists(lists[m // 2: ]) return self.mergeTwoLists(left, right) def mergeTwoLists(self, list1: Optional[ListNode], List2: Optional[ListNode]) -> Optional[ListNode]: cur = dummy = ListNode(x=0) while list1 and List2: if list1.val < List2.val: cur.next = list1 list1 = list1.next else: cur.next = List2 List2 = List2.next cur = cur.next cur.next = list1 if list1 else List2 return dummy.next
算法刷题记录 文章被收录于专栏
刷题,记录牛客的101