Kth Largest Element in a Stream(C++数据流中的第 K 大元素)

459 篇文章 1 订阅

解题思路:

(1)使用优先队列,将其改为小根堆,为后期的第K大元素排在队首

(2)参考网址:https://leetcode.com/problems/kth-largest-element-in-a-stream/discuss/790948/C%2B%2B-Min-Heap-Solution

class KthLargest {
private:
    struct comp {
        bool operator()(const int &a,const int &b) {
            return a>b;
        }
    };
    
    priority_queue<int,vector<int>,comp> pq;
    int size;

public:
    KthLargest(int k, vector<int>& nums) {
        size = k;
        for(auto &w:nums) {
            pq.push(w);
            if(pq.size()>size) pq.pop();
        }
    }
    
    int add(int val) {
        pq.push(val);
        if(pq.size()>size) pq.pop();
        return pq.top();
    }
};

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值