def merge(a,b):
c=[]
l,r=0,0
while l<len(a) and r<len(b):
if a[l]<b[r]:
c.append(a[l])
l+=1
elif a[l]>b[r]:
c.append(b[r])
r+=1
if l==len(a):
c+=b[r:]
else:
c+=a[l:]
return c
def mergeSort(nums):
if len(nums)<2:
return nums
mid=len(nums)//2
left=mergeSort(nums[:mid])
right=mergeSort(nums[mid:])
return merge(left,right)
a=[3,2,4,1,5,7,6]
print(mergeSort(a))
148.排序链表
leetcode 练习题
class Solution(object):
def merge(self,l1,l2):
l=ListNode(0)
p=l
while l1 and l2:
if l1.val<l2.val:
p.next=l1
l1=l1.next
else:
p.next=l2
l2=l2.next
p=p.next
p.next=l1 or l2
return l.next
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
slow,fast=head,head
while fast and fast.next:
prev=slow
slow=slow.next
fast=fast.next.next
prev.next=None
l1=self.sortList(head)
l2=self.sortList(slow)
return self.merge(l1,l2)