[LeetCode][Java]Find Median from Data Stream
2015-11-01 21:03
429 查看
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:
[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
https://leetcode.com/problems/find-median-from-data-stream/
找出中位数,暴力O(n^2)超时。
O(nlogn)的做法是开两个堆(java用优先队列代替)。
最小堆放小于中位数的一半,最大堆放较大的另一半。
addNum操作,把当前的num放到size小的堆中,通过2次poll-add操作,保证了最小堆中的所有数都小于最大堆中的数。
findMedian操作,如果size不同,就是其中一个堆顶,否则就是连个堆顶的数相加除以2。
class MedianFinder { private Queue<Integer> max = new PriorityQueue<Integer>(Collections.reverseOrder()); private Queue<Integer> min = new PriorityQueue<Integer>(); // Adds a number into the data structure. public void addNum(int num) { if(max.size() < min.size()){ max.add(num); min.add(max.poll()); max.add(min.poll()); }else{ min.add(num); max.add(min.poll()); min.add(max.poll()); } } // Returns the median of current data stream public double findMedian() { if(max.size() < min.size()){ return min.peek(); }else if(max.size() > min.size()){ return max.peek(); }else{ return (min.peek() + max.peek()) / 2.0; } } };
上面的做法,有多余的poll-add操作,可以做些优化。
// Adds a number into the data structure. public void addNum(int num) { max.add(num); min.add(max.poll()); if(max.size() < min.size()){ max.add(min.poll()); } }
相关文章推荐
- Java调用R(一)
- 疯狂java讲义4.2--浮点数转换成人民币读法
- 解决Java项目库文件困扰的两个eclipse插件
- Java反射机制与实例
- Java 接口回调
- java中的垃圾收集器
- java基本数据类型
- java中的Arrays类
- java基础1
- Java基本语法小结
- spring 注解 事务
- Java抽象类与接口的区别
- Spring事务管理
- spring 注解 aop
- SpringIOC_init和destory和执行流程
- java 验证码的制作 t图片制作
- javase实现银行转账
- struts之拦截器
- JDK8安装时错误1335的解决
- 利用反射获取Java类中的静态变量名及变量值