Find Median from Data Stream
2016-07-21 02:46
267 查看
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:
分析:
使用两个heap,一个min heap(root的值最小) and max heap (root的值最大)。保持两个heap的size差别最大为1, 而且maxHeap的size不能比minHeap的size 小。
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
分析:
使用两个heap,一个min heap(root的值最小) and max heap (root的值最大)。保持两个heap的size差别最大为1, 而且maxHeap的size不能比minHeap的size 小。
public class MedianFinder { PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>() { public int compare(Integer x, Integer y) { return y - x; } }); public static void main(String[] args) { MedianFinder mf = new MedianFinder(); mf.addNum(2); mf.addNum(3); System.out.println(mf.findMedian()); } // Adds a number into the data structure. public void addNum(int num) { if (maxHeap.isEmpty()) { maxHeap.offer(num); return; } if (num < maxHeap.peek()) { maxHeap.offer(num); } else { minHeap.offer(num); } if (maxHeap.size() > minHeap.size() + 1) { minHeap.offer(maxHeap.poll()); } else if (maxHeap.size() < minHeap.size()) { maxHeap.offer(minHeap.poll()); } } // Returns the median of current data stream public double findMedian() { if (maxHeap.size() == minHeap.size()) { return (maxHeap.peek() + minHeap.peek()) / 2.0; } else { return maxHeap.peek(); } } };
相关文章推荐
- 如何让TinyMCE Advanced编辑器去除换行增加的P标签并获取内容值
- LA 4126 Password Suspects
- Ubuntu 16.04 Steam
- ORACLE PL/SQL 实例精解之第五章 条件控制:CASE语句
- js的隐式转换问题
- C之文件读写
- 375. Guess Number Higher or Lower II
- Ros学习注意点
- CAAnimation 类
- sqlite no such table
- Zendframework application 引导过程
- 占坑[概率dp] poj 2096 Collecting Bugs
- [React Native] Up and Running
- ECMAScript中的真值和假值
- 2016年7月21日
- 贰:Modbus常用功能码协议详解
- swift中使用OC的方法;在OC中调用swift方法
- BZOJ3868 : The only survival
- Maya 脚本控制物体自转
- ACM-线段树