- 第k大用小顶堆
- 小顶堆 用序号小的减序号大的
关键
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> smallHeap=new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
for (int num : nums) {
if (smallHeap.size()<k){
smallHeap.add(num);
}else {
if (smallHeap.peek()<num){
smallHeap.poll();
smallHeap.offer(num);
}
}
}
return smallHeap.peek();
}
}