题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
思路
我们把所有输入分为两个堆,最小堆存放前一半数值比较小的数,最大堆存放后一半数值比较大的数。
为了保证数据平均分配,我们要让两个堆数据的数目之差不超过1,因此,在总数目为偶数的时候,我们要把新数据插入最小堆,否则插入最大堆。
同时我们还要保证最大堆的所有元素都小于最小堆,在长度为偶数的时候,我们目的是插入最小堆,那么如果此时最大堆的最大元素大于要插入的元素,那么我们就取出最大堆的元素,并以插入元素代替,再把弹出的元素插入最小堆中。
当长度为奇数的时候同理。
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
// 小顶堆:所有的值都比大顶堆大
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// 大顶堆,改版比较器,默认容器大小随便设置(两个堆都是自动增加,无限大)
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(11,
new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
public void Insert(Integer num) {
// 判断两个堆的数据数量是否为偶数
if (((minHeap.size()+maxHeap.size())&1)==0) {
//当大顶堆没有数值时,表明两个堆都为空,直接放在大顶堆;
//否则,首先将num和小顶堆最小值比较,目的是保证将num和小顶堆中最小的值放入maxHeap中
if(!maxHeap.isEmpty()&&num>minHeap.peek()) {
minHeap.offer(num);
num=minHeap.poll();
}
maxHeap.offer(num);
}else{ // 同理
if(num<maxHeap.peek()) {
maxHeap.offer(num);
num=maxHeap.poll();
}
minHeap.offer(num);
}
}
public Double GetMedian() {
double result = 0.0;
if(((minHeap.size()+maxHeap.size())&1)==0){
result = (minHeap.peek()+maxHeap.peek())/2.0;
}else{
result = maxHeap.peek();
}
return result;
}
}