其他分享
首页 > 其他分享> > 703. Kth Largest Element in a Stream(Leetcode每日一题-2021.02.11)

703. Kth Largest Element in a Stream(Leetcode每日一题-2021.02.11)

作者:互联网

Problem

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.

Constraints:

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

Solution

class KthLargest {
public:

    priority_queue<int, vector<int>, greater<int>>s;
    int _k;

    KthLargest(int k, vector<int>& nums) {
        _k = k;
        for(auto num:nums)
        {
            if(s.size() < _k)
            {
                s.push(num);
            }
            else if(num > s.top())
            {
                s.pop();
                s.push(num);
            }
        }
    }
    
    int add(int val) {
        if(s.size() < _k)
        {
            s.push(val);
        }
        else if(val > s.top())
        {
            s.pop();
            s.push(val);
        }

        return s.top();

    }
};

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

标签:2021.02,11,kthLargest,return,val,Stream,int,KthLargest,add
来源: https://blog.csdn.net/sjt091110317/article/details/113788531