703. Kth Largest Element in a Stream

https://leetcode.com/problems/kth-largest-element-in-a-stream/description/

class KthLargest {
public:
    priority_queue<int> q;
    int k;
    KthLargest(int k, vector<int> nums) {
        this->k = k;
        for (auto &i : nums)
            add(i);
    }
    
    int add(int val) {
        if (q.size() < k) {
            q.push(-val);
        }
        else {
            if (val > -q.top()) {
                q.pop();
                q.push(-val);
            }
        }
        return -q.top();
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */

 

posted @ 2018-11-18 13:57  JTechRoad  阅读(75)  评论(0编辑  收藏  举报