小米 10T、10T Pro 開始接收 Android 11 更新
阿新 • • 發佈:2021-02-07
給你連結串列的頭結點 head ,請將其按 升序 排列並返回 排序後的連結串列 。
list對應的歸併排序
def sortList(nums):
n = len(nums)
if n < 2:
return nums
mid=n//2
left=merge(nums[:mid])
right=merge(nums[mid:])
ans=[]
i = j = 0
while i < len(left) and j < len(right):
if left[i]<right[ j]:
ans.append(left[i])
i += 1
else:
ans.append(right[j])
j+=1
if i == len(left):
ans.extend(right[j:])
else:
ans.extend(left[i:])
return ans
用排序演算法的歸併演算法
class ListNode:
def __init__(self,val=0,next=None):
self.val= val
self.next=next
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
slow=head
fast=head.next
while fast and fast.next:
slow=sloe.next
fast=fast.next.next
mid=slow.next
slow.next=None
left=self.sortList(head)
right=self.sortList(mid)
p=ans= ListNode()
while left and right:
if left.val<right.val:
p.next=left
left=left.next
else:
p.next=right
right=right.next
p=p.next
p.next=left if left else right
return ans.next