leetcode076 数组中的第 K 个最大元素
public static void main(String[] args) {
int[] nums = new int[]{3,2,1,5,6,3,4};
System.out.println(findKthLargest(nums,2));
}
/**
* 快速排序
*/
public static int findKthLargest(int[] nums, int k) {
int low = 0;
int high = nums.length-1;
quickSort(nums,low,high);
//取第k大个数值
return nums[nums.length-k];
}
public static void quickSort(int[] nums,int low,int high){
//避免low>=high的时候陷入死循环,stackoverfolw了
if (low>=high){
return;
}
int end = high;
int start = low;
//首位数值做为游标,且首位此时表示空位(暂存空位),等待满足条件的数据写入
int cursor = nums[low];
while (low < high) {
//这里nums[high] > cursor需要改成nums[high] >= cursor,不然0位的3会和5位的3陷入死循环中,导致high一直不变
while (low < high && nums[high] >= cursor) {
--high;
}
//从后开始遍历高位区,小于游标的数据写入低位区间的暂存空位
nums[low] = nums[high];
//同上,没有等于号的话,第一位会死循环,导致low一直不变
while (low < high && nums[low] <= cursor) {
++low;
}
//从前开始遍历低位区,大于游标的数据写入高位区间的暂存空位
nums[high] = nums[low];
}
//将游标填补在最终的暂存空位上,左边位小于游标的值,右边为大于游标的值
nums[low] = cursor;
//同上,两者取一个就可以,避免low>=high的时候陷入死循环,stackoverfolw了
if (start < low - 1) {
quickSort(nums, start, low - 1);
}
if (low + 1 < end) {
quickSort(nums, low + 1, end);
}
}