每日一扣912. 排序数组(快速排序)
Posted 李彬的技术笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每日一扣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
以上是关于每日一扣912. 排序数组(快速排序)的主要内容,如果未能解决你的问题,请参考以下文章