[LeetCode] Kth Largest Element in a Stream

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.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class KthLargest {
priority_queue<int, vector<int>, greater<int>> pq;
int k;
void pop() {
while(pq.size() > k) pq.pop();
}
public:
KthLargest(int k, vector<int>& nums): k(k) {
for(auto& n : nums) pq.push(n);
pop();
}

int add(int val) {
pq.push(val);
pop();
return pq.top();
}
};

/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
* int param_1 = obj->add(val);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/09/PS/LeetCode/kth-largest-element-in-a-stream/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.