(算法)数据流中的第K⼤元素————<堆>

1. 题⽬链接:703.数据流中的第K⼤元素

2. 题⽬描述:

3. 解法(优先级队列):

算法思路:

我相信,看到TopK 问题的时候,兄弟们应该能⽴⻢想到「堆」,这应该是刻在⻣⼦⾥的记忆。

 C++算法代码:

class KthLargest 
{
public:
    //创建一个小根堆
    priority_queue<int,vector<int>,greater<int>>heap;
    int _k;
    KthLargest(int k, vector<int>& nums) 
    {
        _k=k;
        for(int key:nums)
        {
            heap.push(key);
            if(heap.size()>k)
            {
                heap.pop();
            }
        }
    }
    
    int add(int val) 
    {
        heap.push(val);
        if(heap.size()>_k)
        {
            heap.pop();
        }
        return heap.top();
    }
};

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

Java算法代码:

class KthLargest
{
	// 创建⼀个⼤⼩为 k 的⼩根堆 
	PriorityQueue<Integer> heap;
	int _k;
	public KthLargest(int k, int[] nums)
	{
		_k = k;
		heap = new PriorityQueue<>();
		for (int x : nums)
		{
			heap.offer(x);
			if (heap.size() > _k)
			{
				heap.poll();
			}
		}
	}

	public int add(int val)
	{
		heap.offer(val);
		if (heap.size() > _k)
		{
			heap.poll();
		}
		return heap.peek();
	}
}
/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

课堂随笔

感谢支持~~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值