Leetcode: 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

最大最小堆

复杂度

时间 O(logN) insert, O(1) query, 空间 O(N)

思路

维护一个最大堆,一个最小堆。最大堆存的是到目前为止较小的那一半数,最小堆存的是到目前为止较大的那一半数,这样中位数只有可能是堆顶或者堆顶两个数的均值。而维护两个堆的技巧在于判断堆顶数和新来的数的大小关系,还有两个堆的大小关系。我们始终维护MaxHeap>=MinHeap

 

With the help of java 8, you can simply write this (no initial capacity needed any more) :

PriorityQueue<Integer> max = new PriorityQueue(Collections.reverseOrder());
 1 class MedianFinder {
 2     // max queue is always larger or equal to min queue
 3     PriorityQueue<Integer> min = new PriorityQueue();
 4     PriorityQueue<Integer> max = new PriorityQueue(1000, Collections.reverseOrder()); // see above
 5     // Adds a number into the data structure.
 6     public void addNum(int num) {
 7         max.offer(num);
 8         min.offer(max.poll());
 9         if (max.size() < min.size()){
10             max.offer(min.poll());
11         }
12     }
13 
14     // Returns the median of current data stream
15     public double findMedian() {
16         if (max.size() == min.size()) return (max.peek() + min.peek()) /  2.0;
17         else return max.peek();
18     }
19 };

 

当然其它比较笨的办法可以binary search插入arraylist,保持有序性

转载于:https://www.cnblogs.com/EdwardLiu/p/5081437.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值