mcxen / note

1 stars 0 forks source link

更新215.题目 #21

Closed mcxen closed 2 months ago

mcxen commented 2 months ago
class Solution {
    public int findKthLargest(int[] nums, int k) {
        //最小堆,堆顶就是最小,比较元素和堆顶的大小,如果比他大,就更新这个堆
        PriorityQueue<Integer> heap = new PriorityQueue<>(k, (a,b)->(a-b));
        for (int i = 0; i < nums.length; i++) {
            if (i < k) heap.add(nums[i]);
            else{
                if (heap.peek() < nums[i]) {
                    heap.poll();
                    heap.add(nums[i]);
                }

            }
//            System.out.println(heap.peek());
        }
        return heap.peek();
    }
}