三种方法 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();
}
}