leetcode703 数据流中的第k大元素

用优先队列保存k个最大的元素值

class KthLargest {
public:
    KthLargest(int k, vector<int> nums) {
        size = k;
        for(int num:nums)
        { 
            pq.push(num);   //要先push进来排序后再pop
            if(pq.size()>size) pq.pop();
        }
    }
    int add(int val) {
        pq.push(val);   
        if(pq.size()>size) pq.pop();
        return pq.top();
    }
        
    
private:
    priority_queue<int,vector<int>,greater<int>> pq;  //由于要使top元素为第k个元素,则队列中只可保存k个元素,且要按照升序排列
    int size;
};

参考
https://leetcode.com/problems/kth-largest-element-in-a-stream/discuss/150609/C%2B%2B-super-easy-28ms-solution-beats-100!

你可能感兴趣的:(leetcode)