【每日一扣】912. 排序数组(快速排序)
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
Solution
快速排序这个就不用说了,闭着眼睛都要能写出来啊!
快速排序实现一:
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
现在这题如果写快速排序必须得选随机基准值才能过,不然会对于极端的用例会超时,补充一个随机选择基准值的解法:
import random
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:
p = self.partition(arr, low, high)
self.qsort(arr, low, p-1)
self.qsort(arr, p+1, high)
def partition(self, arr, low, high):
i = low - 1
p = random.randint(low, high)
arr[p], arr[high] = arr[high], arr[p]
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
李彬的技术笔记
编程、投资、生活
Official Account
点个
在看
你最好看