描述
有一个整数数组,请你根据快速排序的思路,找出数组中第 k大的数。
给定一个整数数组 ,同时给定它的大小n和要找的 ,请返回第 大的数(包括重复的元素,不用去重),保证答案存在。
示例1
输入:
[1,3,5,2,2],5,3
复制返回值:
2
复制
示例2
输入:
[10,10,9,9,8,7,5,6,4,3,4,2],12,3
复制返回值:
9
复制说明:
去重后的第3大是8,但本题要求包含重复的元素,不用去重,所以输出9
k趟冒泡排序
public int findKth(int[] a, int n, int K){
// 冒泡k次
for (int i = 0; i < K; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr[n - K];
}
创建一个大小为k的小根堆
public int findKth(int[] a, int n, int K){
// 占存 第k大的值
PriorityQueue<Integer> queue = new PriorityQueue<>(K);
// n * 调整 lgk
for (int num : a) {
if (queue.isEmpty() || num > queue.peek()) {
if (queue.size() >= K) {
queue.poll();
}
queue.add(num);
}
}
return queue.isEmpty() ? 0 : queue.peek();
}