forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKth Largest Element in a Stream.cpp
51 lines (42 loc) · 1.21 KB
/
Kth Largest Element in a Stream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class KthLargest {
int k;
priority_queue<int, vector<int>, greater<int>> minheap;
int n;
public:
KthLargest(int k, vector<int>& nums) {
this->k=k;
this->n=nums.size();
// push the initial elements in the heap
for(auto x : nums){
minheap.push(x);
}
// if the no. of elements are greater than k then remove them
while(n>k){
minheap.pop();
n--;
}
}
int add(int val) {
// if heap is empty or no. of elements are less than k then add the input
if(minheap.empty() || n<k){
minheap.push(val);
this->n=n+1;
}
// else compare it with top
else{
int minn=minheap.top();
// if the input is greater than top
if(minn<val){
minheap.pop();
minheap.push(val);
}
}
// at any point of time top of the heap is required ans
return minheap.top();
}
};
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
* int param_1 = obj->add(val);
*/