Skip to main content

🟢 剑指 Offer II 059. 数据流的第 K 大数值

LeetCode 提示

题目难度 简单

原题链接 🔗 leetcode

题解1#

优先队列,会自动从小到大排,poll 和 peek 都是对队列首位进行操作

class KthLargest {    int size;    PriorityQueue<Integer> heap;
    public KthLargest(int k, int[] nums) {        this.heap = new PriorityQueue<>();        this.size = k;
        for (int num : nums) {            this.add(num);        }    }        public int add(int val) {        this.heap.offer(val);        if (this.heap.size() > size) {            this.heap.poll();        }        return this.heap.peek();    }}
/** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */