leetcode@ [295]Find Median from Data Stream
2015-10-27 12:40
423 查看
https://leetcode.com/problems/find-median-from-data-stream/
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4], the median is
3
[2,3], the median is
(2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:
add(1) add(2) findMedian() -> 1.5 add(3) findMedian() -> 2
class MedianFinder { private: priority_queue<int,vector<int>, greater<int> > maxHeap; priority_queue<int> minHeap; public: // Adds a number into the data structure. void addNum(int num) { if(minHeap.empty() || num <= minHeap.top()){ if(minHeap.size() > maxHeap.size()){ maxHeap.push(minHeap.top()); minHeap.pop(); } minHeap.push(num); } else if(maxHeap.empty() || num > maxHeap.top()){ if(maxHeap.size() > minHeap.size()){ minHeap.push(maxHeap.top()); maxHeap.pop(); } maxHeap.push(num); } else{ if(maxHeap.size() >= minHeap.size()) minHeap.push(num); else if(minHeap.size() > maxHeap.size()) maxHeap.push(num); } } // Returns the median of current data stream double findMedian() { if(minHeap.size() == maxHeap.size()) return (double) (minHeap.top() + maxHeap.top()) / 2.0; else if(minHeap.size() > maxHeap.size()) return (double) minHeap.top(); else return (double) maxHeap.top(); } }; // Your MedianFinder object will be instantiated and called as such: // MedianFinder mf; // mf.addNum(1); // mf.findMedian();
相关文章推荐
- IOCCC.1984.anonymous.c.解析
- 转载!!:网络协议学习导图
- 关于java命名规范及注释,并将javadoc的生成html
- Cocos2dx基础
- javascript(三)原型 原型链 Object.prototype
- UML基础概述
- 37-java数字猜大小
- HDU 5506(GT and set)
- Linux下的PCI总线驱动
- HDU 5506(GT and set)
- jquery 中js的总结问题
- android 如何导出jar包
- openwrt 常用命令
- Android之Handler详解
- 3.4 Queue via Stacks
- linux中Jetty的安装和配置
- 一个实例说明一个程序的编写步骤(Python语言)
- 依赖注入揭秘
- 端口重定向
- 在一个frame设置四个组件