其他分享
首页 > 其他分享> > Leetcode学习笔记:#703. Kth Largest Element in a Stream

Leetcode学习笔记:#703. Kth Largest Element in a Stream

作者:互联网

Leetcode学习笔记:#703. Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

实现:

   class KthLargest {
        final PriorityQueue<Integer> q;
        final int k;

        public KthLargest(int k, int[] a) {
            this.k = k;
            q = new PriorityQueue<>(k);
            for (int n : a)
                add(n);
        }

        public int add(int n) {
            if (q.size() < k)
                q.offer(n);
            else if (q.peek() < n) {
                q.poll();
                q.offer(n);
            }
            return q.peek();
        }
    }

标签:stream,Stream,int,KthLargest,element,add,Kth,kth,703
来源: https://blog.csdn.net/ccystewart/article/details/90575600