Leetcode 789 Solution

This article provides solution to leetcode question 789 (kth-largest-element-in-a-stream)

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

Solution

class KthLargest {
    priority_queue<int, vector<int>, greater<int>> q;
    int m_k;

public:
    KthLargest(int k, vector<int> nums) {
        m_k = k;
        for (int i = 0; i < nums.size(); i++)
        {
            q.push(nums[i]);

            if (q.size() > k)
                q.pop();
        }
    }

    int add(int val) {
        q.push(val);
        if (q.size() > m_k)
            q.pop();
        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);
 */