2024每日刷题(132)
Leetcode—295. 数据流的中位数
实现代码
class MedianFinder {
public:MedianFinder() {}void addNum(int num) {if(maxHeap.empty() || num < maxHeap.top()) {maxHeap.push(num);} else {minHeap.push(num);}if(maxHeap.size() < minHeap.size()) {maxHeap.push(minHeap.top()), minHeap.pop();} else if(maxHeap.size() > minHeap.size() + 1) {minHeap.push(maxHeap.top()), maxHeap.pop();}}double findMedian() {if(maxHeap.size() == minHeap.size()) {return maxHeap.top() / 2.0 + minHeap.top() / 2.0;} else {return maxHeap.top() * 1.0;}}
private:priority_queue<int> maxHeap;priority_queue<int, vector<int>, greater<>> minHeap;
};/*** Your MedianFinder object will be instantiated and called as such:* MedianFinder* obj = new MedianFinder();* obj->addNum(num);* double param_2 = obj->findMedian();*/
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!