【算法题】数据流中的中位数

题目描述

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

分析
用一个大顶堆、一个小顶堆实现,其中大顶堆保存的是较小的元素,则堆顶是这些元素中的最大值;小顶堆保存的是较大的元素,则堆顶是这些元素中的最小值。则两个堆的堆顶分别保存了数据流中的中心值,那么当数据流总数为偶数时,中位数是大顶堆和小顶堆堆顶元素的平均;当数据流总数为奇数时,中位数是大顶堆堆顶元素。

代码(已AC)

import java.util.Comparator;
import java.util.PriorityQueue;

public class Solution {
    int count = 0;
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(11 ,new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    });

    public void Insert(Integer num) {
        if(count%2==0){
            minHeap.offer(num);
            maxHeap.offer(minHeap.poll());
        }else{
            maxHeap.offer(num);
            minHeap.offer(maxHeap.poll());
        }
        count++;
    }

    public Double GetMedian() {
        if(count %2 ==0) return (double) (minHeap.peek() + maxHeap.peek()) / 2;
        else return (double) maxHeap.peek();
    }


}
原创文章 28 获赞 22 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Steven_L_/article/details/105936960