对于海量数据以及流的数据,要考虑到使用最大堆与最小堆来管理。
[最大堆 | 左边最大 leftMax] | 右边最小rightMin | 最小堆] |
(最大堆中的数据始终要保持小于最小堆中的数据)
当数据总数为偶数时,新加入的数据要加入最小堆。但在加入最小堆之前先进入最大堆进行筛选,把最大堆中的最大数据替换出来加入最小堆。奇数时反之。
数据流处理完毕后,最大堆中的所有数据都小于最小堆中的数据,这时中位数就是最大堆根节点与最小堆根节点相加 / 2,或者是最小堆的根节点(数据总数是奇数时,最后一个数据落入小堆,所以奇数就是返回minHeap)。
import java.util.*;
public class Solution {
private int count = 0;
//构建小根堆
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
//构建大根堆
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
return