Loading

TopK

https://mp.weixin.qq.com/s/FFsvWXiaZK96PtUg-mmtEw

  1. 数据流中的第 K 大元素

https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/

class KthLargest {
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        //pq = new PriorityQueue<Integer>();
        for(int x : nums)
            add(x);
    }
    
    public int add(int val) {
        pq.offer(val);//Inserts the specified element into this priority queue.
        if(pq.size() > k){
            pq.poll();
        }
        return pq.peek();
//Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
    }
}
posted @ 2021-12-14 09:41  Zhbeii  阅读(70)  评论(0)    收藏  举报