本文主要是介绍Leetcode—295. 数据流的中位数【困难】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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();*/
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!
这篇关于Leetcode—295. 数据流的中位数【困难】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!