Kth Largest Element in a Stream

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Returns the element representing the kth largest element in the stream.

 

Example:

Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]

Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

class KthLargest
{
public:
    priority_queue<intvector<int>, greater<int>> q;
    int len;
    KthLargest(int kvector<int&nums)
    {
        len = k;
        for (int i = 0i < nums.size(); i++)
        {
            q.push(nums[i]);
            if (q.size() > k)
                q.pop();
        }
    }

    int add(int val)
    {
        q.push(val);
        if (q.size() > len)
            q.pop();
        return q.top();
    }
};

int main()
{
    vector<intnums = {4582};
    int k = 3;
    KthLargest kthLargest(knums);

    cout << "[";
    cout << kthLargest.add(3<< ", ";
    cout << kthLargest.add(5<< ", ";
    cout << kthLargest.add(10<< ", ";
    cout << kthLargest.add(9<< ", ";
    cout << kthLargest.add(4);
    cout << "]";

    return 0;
}


No comments:

Post a Comment