标签:qsort more bsp app href pre 排序 限制 提示
Difficulty: 中等
给你一个整数数组 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]:
left, right = 0, len(nums)-1
self.qSort(nums, left, right)
return nums
def qSort(self, arr, low, high):
if len(arr) <= 1:
return arr
if low < high:
pivot = self.partition(arr, low, high)
self.qSort(arr, low, pivot-1)
self.qSort(arr, pivot+1, high)
def partition(self, arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
快速排序实现二:
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
# 快速排序
less = []
more = []
pivot_list = []
if len(nums) <= 1:
return nums
else:
pivot = nums[0]
for item in nums:
if item < pivot:
less.append(item)
elif item > pivot:
more.append(item)
else:
pivot_list.append(item)
less = self.sortArray(less)
more = self.sortArray(more)
return less + pivot_list + more
冒泡排序,不过超出了时间限制,没有通过。
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
if not nums:
return []
num_len = len(nums)
for i in range(num_len-1,0,-1):
for j in range(i):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
return nums
插入排序,同样也超出了时间限制,没有通过。
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
if not nums:
return []
num_len = len(nums)
for i in range(1, num_len):
key = nums[i]
j = i - 1
while j >= 0 and key < nums[j]:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = key
return nums
标签:qsort more bsp app href pre 排序 限制 提示
原文地址:https://www.cnblogs.com/swordspoet/p/14508888.html