给你一个整数数组 nums
,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1] 输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0] 输出:[0,0,1,1,2,5]
提示:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
'''
归并排序
'''
n = len(nums)
helper = [0]*n
self.mergeSort(nums,0,n-1,helper)
return nums
def mergeSort(self,nums,left,right,helper):
"""
nums[left,right]局部有序
"""
if left>=right:
return
mid = left + (right-left)//2
self.mergeSort(nums,left,mid,helper)
self.mergeSort(nums,mid+1,right,helper)
self.merge(nums,left,right,helper)
def merge(self,nums,left,right,helper):
"""
合并有序数组
"""
for i in range(left,right+1):
helper[i] = nums[i]
mid = left +(right-left)//2
i = left
j = mid + 1
k = left
while i <= mid and j <= right:
if helper[i] <= helper[j]:
nums[k] = helper[i]
k+=1
i+=1
else:
nums[k] = helper[j]
k+=1
j+=1
while i<=mid:
nums[k] = helper[i]
k+=1
i+=1
while j<=right:
nums[k] = helper[j]
k+=1
j+=1