數據流中的中位數

題目描述

如何得到一個數據流中的中位數?如果從數據流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從數據流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。我們使用Insert()方法讀取數據流,使用GetMedian()方法獲取當前讀取數據的中位數。

解題思路

先創建兩個堆,一個堆是大根堆,另一個堆是小根堆,用一個變量來記錄數據流的個數。注意的是,當count爲偶數的時候,把數據加進大根堆上,然後在大根堆上彈出一個數到小根堆上,當count爲奇數的時候,把數據加進小根堆上,然後在小根堆上彈出一個數放在大根堆上。取平均值的時候,當count 爲偶數的時候,取出大根堆和小根堆的堆頂數然後平均,當count爲奇數的時候,取出小根堆堆頂的數就是平均值了

import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
    public int count = 0; // 用來記錄這個數據流的個數
    // 這個堆本來就是小根堆,而且還是個完全二叉樹
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
        public int compare(Integer o1, Integer o2){
            return o2 - o1;
        }
    });
    public void Insert(Integer num) {
        if(count % 2 == 0){
            maxHeap.offer(num);
            minHeap.offer(maxHeap.poll());
        }else{
            minHeap.offer(num);
            maxHeap.offer(minHeap.poll());
        }
        count++;
    }

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


}

以上就是這道題的解答。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章