解法一:維護最大最小值 -> 堆 -> k個元素的最小值堆
class Solution {public int findKthLargest(int[] nums, int k) {// 維護最大最小值 -> 堆 -> k個元素的最小值堆PriorityQueue<Integer> heap = new PriorityQueue<>((n1, n2) -> n1 - n2);for (int i = 0; i < nums.length; i++) {heap.offer(nums[i]);if (heap.size() > k) {// 維護k個元素的最小值堆heap.poll();}}return heap.peek();}
}
注意:
- 當堆元素個數大于k時,要剔除元素:
heap.poll()