703. Kth Largest Element in a Stream

Problem description:

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.

Example:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums’ length ≥ k-1 and k ≥ 1.

 1 class KthLargest {
 2   PriorityQueue<Integer> pq;
 3   int k;
 4   public KthLargest(int k, int[] nums) {
 5     pq = new PriorityQueue<>();
 6     this.k = k;
 7     for (int num : nums) {
 8       add(num);
 9     }
10   }
11 
12   public int add(int num) {
13     if (pq.size() < k) {
14       pq.add(num);
15     }
16     else if (pq.peek() < num) {
17       pq.poll();
18       pq.add(num);
19     }
20     return pq.peek();
21   }
22 }

 

posted @ 2020-12-16 07:47  北叶青藤  阅读(96)  评论(0编辑  收藏  举报