what is Quick select?
快速选择是一种从无序列表找到第k小元素的选择算法。它从原理上来说与快速排序有关。同样地,它在实际应用是一种高效的算法,具有很好的平均时间复杂度,然而最坏时间复杂度则不理想。
快速选择及其变种是实际应用中最常使用的高效选择算法。
总体而言,Quick select
采用和Quick sort
类似的步骤。首先选定一个pivot
,然后根据每个数字与该pivot
的大小关系将整个数组分为两部分。那么与Quick sort
不同的是,Quick select
只考虑所寻找的目标所在的那一部分子数组,而非像Quick sort
一样分别再对两边进行分割。正是因为如此,Quick select
将平均时间复杂度从O(nlogn)
降到了O(n)。
Quick select 算法描述
Input: array nums, int k. (find kth smallest element in an unsorted array)
Output: int target
- Choose an element from the array as pivot, exchange the position of pivot and number at the end of the array.
- _The pivot can either be the end element or a random chosen e