流式数据中位数

发布时间 2023-03-27 00:46:45作者: zhengbiyu

解决策略

  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();
    }
}