703_数据流中的第K大元素

703_数据流中的第K大元素

 

package 队列.优先级队列;
/**
 * https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/
 * @author Huangyujun
 *
 */

import java.util.Comparator;
import java.util.PriorityQueue;

public class _703_数据流中的第K大元素 {
    
    PriorityQueue<Integer> pq;//大根堆
    int k;

    public _703_数据流中的第K大元素(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);
        if (pq.size() > k) {
            pq.poll();
        }
        return pq.peek();
    }

}

 

posted @ 2021-12-19 23:42  一乐乐  阅读(10)  评论(0编辑  收藏  举报