用优先队列存储前k大元素,堆顶是第k大元素,每一次添加一个元素道优先队列,如果队列长度大于k就pop堆顶元素
参考https://blog.csdn.net/qq_41687938/article/details/117827166
class KthLargest { public: priority_queue<int,vector<int>,greater<int>>pq; int k; KthLargest(int k, vector<int>& nums) { this->k = k; for(auto&x:nums){ add(x); } } int add(int val) { pq.push(val); if(pq.size()>k){ pq.pop(); } return pq.top(); } };