Open larscheng opened 8 months ago
优先队列小顶堆 堆容量为k,超出容量就丢弃堆顶小的元素,最终堆顶就是第k大
class Solution {
public int findKthLargest(int[] nums, int k) {
//小顶堆
PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o1-o2);
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
if (queue.size()>k){
queue.poll();
}
}
return queue.peek();
}
}
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/