数据流中的中位数

优先级队列:默认是最小元素有最大优先级,所以最先poll()出的元素时最小的,本题的maxHeap 用Comparator改写后,最大元素有最大优先级,最先poll()出的元素时最大的

 
public class Solution {
    private int count = 0;
    private PriorityQueue<Integer> minHeap = new PriorityQueue<>();  // 升序排列,堆顶是最小值
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(15, new Comparator<Integer>() {
     public int compare(Integer o1, Integer o2) {
         return o2 - o1;   // 降序排列,堆顶是最大值,poll()会取出最大值
     }
     });//15是队列容量的大小
 
    public void Insert(Integer num) {
        //当此时共有偶数个元素时,新加入的元素先进入最大堆,筛选出最大元素后,加入最小堆,所以最小堆放的都是大数。如果此时是偶数个元素,也可以往最小堆中插入,只是GetMedian方法当count % 2 != 0 的逻辑需要调整下
        if (count % 2 == 0) {
            maxHeap.offer(num);
            int filered = maxHeap.poll();
            minHeap.offer(filered);                
        } else {
            //当此时共有奇数个元素时,新加入的元素先进入最小堆,筛选出最小元素后,加入最大堆,所以最大堆放的都是小数
            minHeap.offer(num);
            int filered = minHeap.poll();
            maxHeap.offer(filered);  
        }
        count++;
    }
 
    public Double GetMedian() {
        if (count % 2 == 0)
            return new Double( (minHeap.peek() + maxHeap.peek()) ) / 2;
        else
            return new Double(minHeap.peek()); //总数为奇数个的时候,最小堆里的是中位数
    }
}
posted @ 2018-10-11 16:56  MarkLeeBYR  阅读(237)  评论(0)    收藏  举报