题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
解法:
建立一个大顶堆和一个小顶堆,确保大顶堆的数都比小顶堆小。且大顶堆的数量总是等于小顶堆或者比小顶堆多一个。
如果两堆数量相同,则中位数为两个堆顶之和除以二
如果大顶堆比小顶堆数量多一,则中位数为大顶堆顶。
//小顶堆
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();
}
}