三种方法 1 排序 2 min heap 3 max heap
我用了3 其实2更直观 只是要想清楚
因为heap是用priority queue实现的 每次只能得到queue head 所以要是min 就要使用k个 记录的是最大的k个
要是max就要使用 n - k + 1个 记录的是最小的几个
再有就是comparator的实现 注意返回值的意义 只要是升序的 那么就返回 int1 - int2
降序就是 int2 - int1
public class Solution {
public int findKthLargest(int[] nums, int k) {
int n = nums.length;
PriorityQueue<Integer> maxHeap = new PriorityQueue ( n - k + 1, new Comparator<Integer>(){
public int compare ( Integer i, Integer j ){
return j - i;
}
});
for ( int i = 0; i < n - k + 1; i ++ )
maxHeap.offer(nums[i]);
for ( int i = n - k + 1; i < n; i ++ ){
if ( nums[i] < maxHeap.peek() ){
maxHeap.poll();
maxHeap.offer( nums[i] );
}
}
return maxHeap.peek();
}
}

本文介绍了一种使用最大堆寻找数组中第K大的元素的方法。通过维护一个大小为n-k+1的最大堆,确保堆中始终保存了数组中的较小部分元素。文章详细解释了如何在遍历数组过程中调整堆,并给出了完整的Java代码实现。
884

被折叠的 条评论
为什么被折叠?



