0%

703. Kth Largest Element in a Stream

minheap O(klogk) time O(k) space

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
class KthLargest {
public:
KthLargest(int k, const vector<int>& nums) : k(k) {
for (int x : nums) {
q.push(x);
if (q.size() > k) {
q.pop();
}
}
}

int add(int val) {
q.push(val);
if (q.size() > k) {
q.pop();
}
return q.top();
}

int k;
priority_queue<int, vector<int>, greater<int>> q;
};

/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
* int param_1 = obj->add(val);
*/