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 integerk
and the stream of integersnums
.int add(int val)
Returns the element representing thekth
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<int, vector<int>, greater<int>> q;int len;KthLargest(int k, vector<int> &nums){len = 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() > len)q.pop();return q.top();}};int main(){vector<int> nums = {4, 5, 8, 2};int k = 3;KthLargest kthLargest(k, nums);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