题解 | #寻找第K大#
寻找第K大
https://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
import java.util.*;
public class Solution {
public int findKth(int[] a, int n, int K) {
// write code here
// 想到了用堆来实现,数组中第k大的数字,肯定是对堆进行poll操作
// 应该选用最大堆,把k-1个数字都挤掉,这样留下的(n - K + 1)个数字中,堆顶就是最大的
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
@Override
public int compare(Integer a,Integer b){
return b.compareTo(a);
}
});
for(int i = 0;i< n;i++){
pq.offer(a[i]);
if(pq.size() > n - K +1){
pq.poll();
}
}
return pq.poll();
}
}
思路很简单,确定用最大堆,并且把堆的size确定,题目就解决了。



腾讯成长空间 5981人发布