一、题目描述
给定整数数组
nums和整数k,请返回数组中第k个最大的元素。请注意,你需要找的是数组排序后的第
k个最大的元素,而不是第k个不同的元素。你必须设计并实现时间复杂度为
O(n)的算法解决此问题。示例 1:
输入:[3,2,1,5,6,4],k = 2 输出: 5示例 2:
输入:[3,2,3,1,2,4,5,5,6],k = 4 输出: 4提示:
1 <= k <= nums.length <= 105-104 <= nums[i] <= 104
题目链接:. - 力扣(LeetCode)
二、解题思路
1、随机选择基准元素
2、根据基准元素将数组分为三部分:[l, left](该部分小于基准元素key)、[left + 1, right - 1](等于基准元素key)、[right, r](大于基准元素key)。
3、计算每部分所包含的元素个数,分别为a 、b = right - left - 1、 c = r - right + 1;
4、分情况讨论:

三、代码
class Solution {
public int findKthLargest(int[] nums, int k) {
return qsort(nums, 0, nums.length-1, k);
}
private int qsort(int[] nums, int l, int r, int k) {
if(l == r) {
return nums[l];
}
//随机选择基准元素
int key = nums[new Random().nextInt(r-l+1) + l];
//根据基准元素将数组划分为三组
int left = l-1, right = r+1, i = l;
while(i < right) {
if(nums[i] < key) {
swap(nums, ++left, i++);
} else if(nums[i] == key) {
i++;
} else {
swap(nums, --right, i);
}
}
//分情况讨论
int b = right - left - 1, c = r - right + 1;
if(c >= k) {
return qsort(nums, right, r, k);
} else if(b + c >= k) {
return key;
} else {
return qsort(nums, l, left, k - b - c);
}
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}






![24-7-9-读书笔记(九)-《爱与生的苦恼》[德]叔本华 [译]金玲](https://i-blog.csdnimg.cn/direct/f5a7872dbe224c64b463e861dedcd9f6.jpeg)






![C# Bitmap类型与Byte[]类型相互转化详解与示例](https://i-blog.csdnimg.cn/direct/a3bbd63c44ac40dd9eafd082c90cd103.jpeg#pic_center)





