随笔 - 171  文章 - 0  评论 - 0  阅读 - 62466

流式数据中位数

解决策略

  1. 建立一个大根堆和一个小根堆,用一个临时变量(count)来统计数据流的个数
  2. 当插入的数字个数为奇数时,使小根堆的个数比大根堆多1;当插入的数字个数为偶数时,使大根堆和小根堆的个数一样多
  3. 当总的个数为奇数时,中位数就是小根堆的堆顶;当总的个数为偶数时,中位数就是两个堆顶的值相加除以2
复制代码
import java.util.Comparator;
import java.util.PriorityQueue;

public class MedianFinder {
    private PriorityQueue<Integer> min = new PriorityQueue<Integer>();
    private PriorityQueue<Integer> max = new PriorityQueue<Integer>(new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
    //统计数据流的个数
    private int count = 0;
    //确保小根堆里面的数 > 大根堆里面的数
    public void insert(Integer num) {
        count++;
        if (count % 2 == 1) {
            //奇数的时候,放在小根堆里面
            max.offer(num);//先从大顶堆过滤一遍
            min.offer(max.poll());
        } else {
            //偶数的时候,放在大根堆里面
            min.offer(num);//先从小顶堆过滤一遍
            max.offer(min.poll());
        }
    }
    public Double getMedian() {
        if (count % 2 == 0) return (min.peek() + max.peek()) / 2.0;
        else return (double) min.peek();
    }
}
复制代码

 

posted on   zhengbiyu  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示