题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
分析
先用PriorityQueue来设置一个小顶堆和大顶堆,
大顶堆用来存较小的数,从大到小排列;小顶堆存较大的数,从小到大排序。显然中位数就是大顶堆的根节点与小顶堆的根节点和的平均数。
当数据个数为偶数的时候,将这个值插入大顶堆中,再将大顶堆中根节点(即最大值)插入到小顶堆中;
当数据个数为奇数的时候,将这个值插入小顶堆中,再讲小顶堆中根节点(即最小值)插入到大顶堆中;
取中位数的时候,如果当前个数为偶数,显然是取小顶堆和大顶堆根结点的平均值;如果当前个数为奇数,显然是取小顶堆的根节点。
import java.util.*;
public class Solution {
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) {
return o2 - o1;
}
});
int count = 0;
public void Insert(Integer num) {
if ((count & 1) == 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 & 1) == 0) { // 有偶数个,取平均值
return new Double(minHeap.peek() + maxHeap.peek()) / 2;
} else {
return new Double(minHeap.peek());
}
}
}