[LeetCode] Find Median from Data Stream
This post shares a very nice solution using two heaps: a max heap for the smaller half and a min heap for the larger half. The code is rewritten below in C++, simplifying addNum
using the logic in Stefan's post.
class MedianFinder { public: // Adds a number into the data structure. void addNum(int num) { maxH.push(num); int t = maxH.top(); maxH.pop(); minH.push(t); int m = maxH.size(), n = minH.size(); if (n > m) { int t = minH.top(); minH.pop(); maxH.push(t); } } // Returns the median of current data stream double findMedian() { int m = maxH.size(), n = minH.size(); if (!m && !n) return 0.0; if (m == n) return (maxH.top() + minH.top()) / 2.0; return (m > n) ? maxH.top() : minH.top(); } private: priority_queue<int, vector<int>, less<int>> maxH; // stores the smaller half priority_queue<int, vector<int>, greater<int>> minH; // stores the larger half }; // Your MedianFinder object will be instantiated and called as such: // MedianFinder mf; // mf.addNum(1); // mf.findMedian();
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· 大模型工具KTransformer的安装
· [计算机/硬件/GPU] 显卡