思路一:链表逐个两两合并(超时了)
参考:leetcode【简单】21、合并两个有序链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def mergeTwoLists(l1,l2):
if not l1:
return l2
elif not l2:
return l1
elif l1.val<l2.val:
l1.next=mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=mergeTwoLists(l1,l2.next)
return l2
res=[]
if not lists:
return None
n = len(lists)
res = lists[0]
for i in range(1,n):
res=mergeTwoLists(lists[i],res)
return res
思路二:分治/二分法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def mergeTwoLists(l1,l2):
if not l1:
return l2
elif not l2:
return l1
elif l1.val<l2.val:
l1.next=mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=mergeTwoLists(l1,l2.next)
return l2
def helper(begin,end):
if begin==end:
return lists[begin]
mid = begin+(end-begin)//2
left = helper(begin,mid)
right = helper(mid+1,end)
return mergeTwoLists(left,right)
if not lists:
return None
return helper(0,len(lists)-1)