Leetcode 23. Merge k Sorted Lists(python)
分治法两两合并,才没有超时
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists)==0: return []
return self.merge(lists,0,len(lists)-1)
def merge(self,lists,l,r):
if l<r:
mid=(l+r)/2
return self.mergeTwoLists(self.merge(lists,l,mid),self.merge(lists,mid+1,r))
return lists[l]
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res=cur=ListNode(0)
while l1 and l2:
if l1.val<l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
cur.next=l1 or l2
return res.next

浙公网安备 33010602011771号