题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
思路:
需要求的是中位数,如果我将 1 2 3 4 5 6 7 8定为最终的数据流 此时的中位数是4+5求均值。为什么是4,为什么是5 利用队列我们就可以看得很清楚,4是前半部分最大的值,肯定是维系在大顶堆 而5是后半部分的最小值,肯定是维系在小顶堆。 问题就好理解了: 使用小顶堆存大数据,使用大顶堆存小数据。这样堆顶一取出就是中位数了。 大小顶堆内部默认都是升序排序。
//小顶堆
private PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
//大顶堆
private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(15,new Comparator<Integer>() {
@Override//换成降序排序
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return 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 new Double(minHeap.peek());//当为计数为奇数的时候小顶堆会比大顶堆多一个
}
}