首先是最经典的Partion函数分治思想与快速排序的经典写法:
快递排序递归部分,只要left<right 则取其某数作为中心点分界,以此类推。
class Solution(object):
def quicksort(self, arr, left, right):
if left < right:
position = self.Partition(arr, left, right)
self.quicksort(arr, left, position-1)
self.quicksort(arr, position+1, right)
return arr
Partion函数部分:
#一个Point的方法,以left为轴心,以 pivot 为分界线将数组中其他元素分为两部分,使得左边部分的数小于等于枢轴,右边部分的数大于等于枢轴
def Partition(self, arr, left ,right):
index = left
pivot = arr[left]
for i in range(left+1, right+1):
if arr[i] < pivot:
index += 1
if i != index:
arr[i], arr[index] = arr[index], arr[i]
arr[index], arr[left] = arr[left], arr[index]
return index
#两个point的方法
def Partition(self, arr, left ,right):
pivot = arr[left]
while left < right:
while left < right and arr[right] > pivot:
right -= 1
arr[left] = arr[right]
while left < right and arr[left] <= pivot:
left += 1
arr[right] = arr[left]
arr[left] = pivot
return left
Partition函数应用:
75. Sort Colors(Medium)
Given an array with n objects colored red, white or blue, sort them **in-place **so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
给定n个红色或白色或蓝色的物品,请按原来的顺序做一个颜色的排序。这里0,1,2分别代表红、白、蓝。
思路: Dutch national flag problem荷兰国旗问题,题目要求不能用库函数,同时要求恒定的空间与一次算法实现,可考虑3次point的Partition函数。
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
first,second,last = 0,0,len(nums)-1
while second <= last:
if nums[second] == 0:
nums[first], nums[second] = nums[second], nums[first]
first += 1
second += 1
elif nums[second] == 1:
second += 1
else:
nums[last], nums[second] = nums[second], nums[last]
last -= 1
215. Kth Largest Element in an Array(Medium)
思路:此题还可以小根堆做,快速排序原理是利用(从小到大)快排的partition操作把数组两边划分成左边小于等于pivot, 右边大于等于pivot。(pivot为基准值),位置记为pivot。 若右边的元素比不少于k个,说明第k大的元素在数组的右边, 否则第k大的元素在数组的左边。
作者:happy_yuxuan
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/leetcode215-shu-zu-zhong-de-di-kge-zui-da-yuan-su-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
l,r = 0, len(nums)-1
k = len(nums) - k
while l <= r:
pivot = self.partition(nums, l, r)
if pivot == k:
return nums[k]
elif pivot < k:
l = pivot +1
else:
r = pivot - 1
def partition(self, arr, left ,right):
pivot = arr[left]
while left < right:
while left < right and arr[right] > pivot:
right -= 1
arr[left] = arr[right]
while left < right and arr[left] <= pivot:
left += 1
arr[right] = arr[left]
arr[left] = pivot
return left
网友评论