目录
1、 1046. 最后一块石头的重量
思路:根据示例发现可以用大根堆(降序)模拟这个过程。
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> heap;
for (auto s : stones)
heap.push(s);
while (heap.size() > 1) {
int a = heap.top();
heap.pop();
int b = heap.top();
heap.pop();
if (a > b)
heap.push(a - b);
}
return heap.size() ? heap.top() : 0;
}
};
2、 703. 数据流中的第 K 大元素
思路:TopK问题使用小根堆堆解决,priority_queue(默认大根堆)的第三个参数为greater<类型>即为小根堆。
class KthLargest {
public:
int _k;
priority_queue<int, vector<int>, greater<int>> heap;
KthLargest(int k, vector<int>& nums) {
_k = k;
for (auto n : nums) {
heap.push(n);
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);
*/