Leetcode刷题 - 在数据流找中位数(Find Median from Data Stream)

方法一:Insertion Sort

1 class MedianFinder { 2 vector<int> store; // resize-able 3 public: 4 /** initialize your data structure here. */ 5 MedianFinder() { 6 7 } 8 9 void addNum(int num) { 10 if (store.empty()) 11 store.push_back(num); 12 else 13 // insert(position, value) 14 // lower_bound(interator first, interator last, num) -> return 15 // return 在range里第一个小于这个num的位置 16 // binary search combined with insertion 17 store.insert(lower_bound(store.begin(), store.end(), num), num); 18 } 19 20 double findMedian() { 21 int n = store.size(); 22 //利用二进制快速判断奇偶数 23 return n & 1 ? store[n/2] : ((double) store[n/2 - 1] + store[n/2])*0.5; 24 } 25 };

方法二:Two Heap

1 class MedianFinder{ 2 //优先队列建立最大堆 3 priority_queue<int> lo; // max heap 4 // 优先队列建立最小堆 5 priority_queue<int, vector<int>, greater<int>> hi; // min heap 6 public: 7 void addNum(int num){ 8 // Add to max heap 9 lo.push(num); 10 // balance step 11 hi.push(lo.top()); 12 13 lo.pop(); 14 15 // maintain size property 16 if(lo.size() < hi.size()){ 17 lo.push(hi.top()); 18 hi.pop(); 19 } 20 } 21 22 double findMedian(){ 23 return lo.size() > hi.size() ? lo.top() : ((double) lo.top() + hi.top())*0.5; 24 } 25 };

 


__EOF__

本文作者cancantrbl
本文链接https://www.cnblogs.com/cancantrbl/p/13652890.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   cancantrbl  阅读(214)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示