用归并实现 k 路合并:
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# 归并
if len(lists) == 0: return None
def merge(start, end):
if end == start:
return lists[start]
mid = start + (end - start) // 2
left = merge(start, mid)
right = merge(mid + 1, end)
return self.mergeTwoLists(left, right)
return merge(0, len(lists) - 1)
def mergeTwoLists(self, l1, l2):
pointer = helper = ListNode()
while l1 and l2:
if l1.val <= l2.val:
pointer.next = l1
l1 = l1.next
else:
pointer.next = l2
l2 = l2.next
pointer = pointer.next
if l1:
pointer.next = l1
else:
pointer.next = l2
return helper.next
网友评论