- tags: Priority Queue,LeetCode101
Using a min heap to keep k elements, top is the Kth largest element.
class KthLargest {
private:
// min heap
priority_queue<int, vector<int>, std::greater<int>> pq;
int K;
public:
KthLargest(int k, vector<int>& nums) {
K = k;
for (auto n: nums) {
add(n);
}
}
int add(int val) {
pq.push(val);
while (pq.size() > K) {
pq.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);
*/