劍-數據流中的中位數

題目描述

如何得到一個數據流中的中位數?如果從數據流中讀出奇數個數值,那麼中位數就是所有數值排序之後位於中間的數值。如果從數據流中讀出偶數個數值,那麼中位數就是所有數值排序之後中間兩個數的平均值。

解法:
建立一個大頂堆和一個小頂堆,確保大頂堆的數都比小頂堆小。且大頂堆的數量總是等於小頂堆或者比小頂堆多一個。
如果兩堆數量相同,則中位數爲兩個堆頂之和除以二
如果大頂堆比小頂堆數量多一,則中位數爲大頂堆頂。
//小頂堆
private static PriorityQueue<Integer> smallTop = new PriorityQueue<>(new Comparator<Integer>() {

	@Override
	public int compare(Integer o1, Integer o2) {
		return o1 - o2;
	}
});

//大頂堆
private static PriorityQueue<Integer> bigTop = new PriorityQueue<>(new Comparator<Integer>() {

	@Override
	public int compare(Integer o1, Integer o2) {
		return o2 - o1;
	}
});

//插入數字總數
private static int number = 0;

//插入數字
public static void Insert(Integer num) {
	//插入大頂堆
	if (number % 2 == 0) {
		smallTop.add(num);
		bigTop.add(smallTop.poll());
		number++;
	//插入小頂堆
	} else {
		bigTop.add(num);
		smallTop.add(bigTop.poll());
		number++;
	}
	//System.out.println("bigtop" + bigTop);
	//System.out.println("smalltop" + smallTop);
}

//獲取中位數
public static Double GetMedian() {
	if(number % 2 == 0){
		return  (bigTop.peek() + smallTop.peek()) / 2.0;
	}else{
		return (double)bigTop.peek();
	}
}


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