首页 > 其他 > 详细

数据流中的中位数

时间:2018-10-11 18:00:36      阅读:124      评论:0      收藏:0      [点我收藏+]

优先级队列:默认是最小元素有最大优先级,所以最先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;
     }
     });//15是队列容量的大小
 
    public void Insert(Integer num) {
        //当此时共有偶数个元素时,新加入的元素先进入最大堆,筛选出最大元素后,加入最小堆,所以最小堆放的都是大数
        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()); //总数为奇数个的时候,最小堆里的是中位数
    }
}

数据流中的中位数

原文:https://www.cnblogs.com/MarkLeeBYR/p/9773495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!