leetcode:Find Median from Data Stream
2016-03-21 23:46
405 查看
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:
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
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
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class MedianFinder { private: priority_queue<int, vector<int>, greater<int>> minHeap; priority_queue<int, vector<int>, less<int>> maxHeap; public: // Adds a number into the data structure. void addNum(int num) { if (maxHeap.size() == minHeap.size()) { if (minHeap.size() != 0 && num > minHeap.top()) { maxHeap.push(minHeap.top()); minHeap.pop(); minHeap.push(num); } else { maxHeap.push(num); } } else { if (num < maxHeap.top()) { minHeap.push(maxHeap.top()); maxHeap.pop(); maxHeap.push(num); } else { minHeap.push(num); } } } // Returns the median of current data stream double findMedian() { if (maxHeap.size() == 0) return 0; if (maxHeap.size() == minHeap.size()) return ((double)minHeap.top()+(double)maxHeap.top())/2; else return (double)maxHeap.top(); } }; // Your MedianFinder object will be instantiated and called as such: // MedianFinder mf; // mf.addNum(1); // mf.findMedian();
相关文章推荐
- 【ML】ICML2015_Unsupervised Learning of Video Representations using LSTMs
- 知识点5:ln链接
- python正则表达式
- The project target (Android N (Preview)) was not properly loaded.
- csh(tcsh)
- PSP记录个人项目耗时情况
- 设计模式学习笔记——状态模式
- 工具类:拉伸一张图片(UIImage分类)
- 项目之RFID天线设计
- requests的content与text导致lxml的解析问题
- Spring源码之ApplicationContext(七)获取消息资源
- JAVA 基础 final关键字
- AndroidAutoLayout 屏幕适配
- Codeforces 400B Inna and New Matrix of Candies 【模拟】
- 图示aidl原理
- Android中SQLite数据库小计
- Android——关于Activity跳转的返回(无返回值和有返回值)——无返回值
- Spring源码之ApplicationContext(六)注册BeanPostProcessor
- 使用scm-manager搭建git/svn 代码管理仓库
- Objective-C探究alloc方法的实现