解题思路:
(1)使用优先队列,将其改为小根堆,为后期的第K大元素排在队首
class KthLargest {
private:
struct comp {
bool operator()(const int &a,const int &b) {
return a>b;
}
};
priority_queue<int,vector<int>,comp> pq;
int size;
public:
KthLargest(int k, vector<int>& nums) {
size = k;
for(auto &w:nums) {
pq.push(w);
if(pq.size()>size) pq.pop();
}
}
int add(int val) {
pq.push(val);
if(pq.size()>size) 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);
*/