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);
*/
标签:KthLargest,val,nums,int,元素,算法,heap,数据流,size
From: https://blog.csdn.net/2301_79580018/article/details/141821879