Skip to content

Commit 8c3b1eb

Browse files
Create kth_largest_element_in_stream.cpp
1 parent aec13b3 commit 8c3b1eb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

kth_largest_element_in_stream.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class KthLargest {
2+
public:
3+
int size;
4+
priority_queue<int, vector<int>, greater<int> > Q;
5+
KthLargest(int k, vector<int>& nums) {
6+
size = k;
7+
for(auto num : nums) {
8+
Q.push(num);
9+
if(Q.size() > k) Q.pop(); //only keep k elements in the Queue
10+
}
11+
}
12+
13+
int add(int val) {
14+
Q.push(val);
15+
if(Q.size() > size) Q.pop();
16+
return Q.top();
17+
}
18+
};
19+
20+
/**
21+
* Your KthLargest object will be instantiated and called as such:
22+
* KthLargest* obj = new KthLargest(k, nums);
23+
* int param_1 = obj->add(val);
24+
*/

0 commit comments

Comments
 (0)