Posted on

Description

Submission

class KthLargest {
    multiset<int> _set;
    int _k;
public:
    KthLargest(int k, vector<int>& nums) {
        for(int x : nums) {
            _set.insert(x);
        }
        _k = k;
    }
    
    int add(int val) {
        _set.insert(val);
        auto iter = _set.end();
        for(int i = 0; i < _k; ++i, iter--);
        return *iter;
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */
class KthLargest {
    priority_queue<int, vector<int>, greater<int>> _pq;
    int _k;
public:
    KthLargest(int k, vector<int>& nums) {
        _k = k;
        for(int x : nums) {
            if(_pq.size() == _k) {
                if(x > _pq.top()) {
                    _pq.pop();
                    _pq.push(x);
                }
            } else {
                _pq.push(x);
            }
        }
    }
    
    int add(int val) {
        if(_pq.size() == _k) {
            if(val > _pq.top()) {
                _pq.pop();
                _pq.push(val);
            }
        } else {
            _pq.push(val);
        }
        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);
 */

Leave a Reply

Your email address will not be published. Required fields are marked *