题目描述
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(1<=K<=n),请返回第K大的数(包括重复的元素,不用去重),保证答案存在。
解题思路
利用大根堆的特点,把数组元素放进大根堆,然后再删除K-1个最大的元素,剩下的最大数就是第K大的数。
代码实现
package heap;
import java.util.PriorityQueue;
public class _寻找第K大的数 {
public static int findKth(int[] a, int n, int K) {
// write code here
PriorityQueue<Integer> pq = new PriorityQueue<>(
(o1, o2) -> o2 - o1);
for(int t:a) {
pq.add(t);
}
for(int i = 1;i < K;i++) {
pq.remove();
}
return pq.peek();
}
public static void main(String[] args) {
System.out.println(findKth(new int[]{10, 10, 9, 9, 8, 7, 5, 6, 4, 3, 4, 2}, 12, 3));
}
}