63.數據流中的中位數

題目描述

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

題目解答

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

    public void Insert(Integer num) {
        if ((count&1) == 0) { // 判斷偶數的高效寫法
            maxHeap.offer(num);
            int filteredMaxNum=maxHeap.poll();
            minHeap.offer(filteredMaxNum);
        }else{
            minHeap.offer(num);
            int filteredMinNum=minHeap.poll();
            maxHeap.offer(filteredMinNum);
        }
        count++;
    }

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


}

左邊:最大堆java

右邊:最小堆ide

 

當數據總數爲偶數時,新加入的元素,應當進入小根堆(注意不是直接進入小根堆,而是經大根堆篩選後取大根堆中最大元素進入小根堆)spa

1.新加入的元素先入到大根堆,由大根堆篩選出堆中最大的元素

2.篩選後的"大根堆中的最大元素"進入小根堆code

當數據總數爲奇數時,新加入的元素,應當進入大根堆(注意不是直接進入大根堆,而是經小根堆篩選後取小根堆中最大元素進入大根堆)
1.新加入的元素先入到小根堆,由小根堆篩選出堆中最小的元素
2.篩選後的"小根堆中的最小元素"進入大根堆
 
最大堆還能夠用lamda表達式定義:
PriorityQueue<Integer> maxHeap=new PriorityQueue<>((o1, o2) -> o2 - o1);
相關文章
相關標籤/搜索