在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int findKthLargest(int[] nums, int k) {
int len = nums.length;
sort(nums, 0, len-1);
return nums[len-k];
}
public void sort(int[] a, int low, int high) {
if(low >= high) {
return;
}
int i, j, standard;
i = low;
j = high;
Random random = new Random();
int index = random.nextInt(high-low+1)+low;
standard = a[index];
while(i < j) {
while(index < j && a[j] >= standard)
j--;
if(index < j) {
a[index] = a[j];
a[j] = standard;
index = j;
}
while(i < index && a[i] <= standard)
i++;
if(i < index) {
a[index] = a[i];
a[i] = standard;
index = i;
}
}
sort(a, low, index-1);
sort(a, index+1, high);
}
}