题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
解题思路
先创建两个堆,一个堆是大根堆,另一个堆是小根堆,用一个变量来记录数据流的个数。注意的是,当count为偶数的时候,把数据加进大根堆上,然后在大根堆上弹出一个数到小根堆上,当count为奇数的时候,把数据加进小根堆上,然后在小根堆上弹出一个数放在大根堆上。取平均值的时候,当count 为偶数的时候,取出大根堆和小根堆的堆顶数然后平均,当count为奇数的时候,取出小根堆堆顶的数就是平均值了
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
public int count = 0; // 用来记录这个数据流的个数
// 这个堆本来就是小根堆,而且还是个完全二叉树
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
return o2 - o1;
}
});
public void Insert(Integer num) {
if(count % 2 == 0){
maxHeap.offer(num);
minHeap.offer(maxHeap.poll());
}else{
minHeap.offer(num);
maxHeap.offer(minHeap.poll());
}
count++;
}
public Double GetMedian() {
if(count % 2 == 0) return ((double)(minHeap.peek() + maxHeap.peek()) / 2);
else return (double)minHeap.peek();
}
}
以上就是这道题的解答。