Skip to content

Commit 1c63d49

Browse files
authored
Create kth-largest-element-in-a-stream.cpp
1 parent 4cea1bc commit 1c63d49

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(nlogk)
2+
// Space: O(k)
3+
4+
class KthLargest {
5+
public:
6+
KthLargest(int k, vector<int> nums) :
7+
k_(k) {
8+
for (const auto& num : nums) {
9+
add(num);
10+
}
11+
}
12+
13+
int add(int val) {
14+
min_heap_.emplace(val);
15+
if (min_heap_.size() > k_) {
16+
min_heap_.pop();
17+
}
18+
return min_heap_.top();
19+
}
20+
21+
private:
22+
const int k_;
23+
priority_queue<int, vector<int>, greater<int>> min_heap_;
24+
};
25+
26+
/**
27+
* Your KthLargest object will be instantiated and called as such:
28+
* KthLargest obj = new KthLargest(k, nums);
29+
* int param_1 = obj.add(val);
30+
*/
31+

0 commit comments

Comments
 (0)