剣はofferデータストリームの中位数Javaを指す

7979 ワード

タイトル
データストリームの中位数をどのように得るかを説明します.データストリームから奇数個の数値を読み出すと、中位数は、すべての数値がソートされた後に中間に位置する数値である.データストリームから偶数個の数値が読み出されると、中位数は、すべての数値が並べ替えられた後の中間の2つの数の平均値となります.Insert()メソッドを用いてデータストリームを読み出し,GetMedian()メソッドを用いて現在の読み出しデータの中位数を取得した.
問題解
 我们可以设置一个大顶堆和一个小顶堆,在每次获取到数据时根据数据是第几个来确定奇偶,从而将每次插入的数分开放入两个堆中,在每次放入完成后,将所在堆的堆顶放入另外一个堆中,从而确保数量的平均以及大小顺序按一定顺序排列,このように、各小天井スタックのデータは大天井スタックよりも大きく、中位数を判断するには2つのスタックの天井を見るだけでよい.
コード#コード#
import java.util.*;

public class Solution {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(); //   
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
        //   
        @Override
        public int compare(Integer i1,Integer i2){
            return i2-i1;//    ,     i1-i2
        }
    });
//Lambda     :
//PriorityQueue Heap=new PriorityQueue<>((Comparator)(o1,o2)->o2-o1);

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

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