题目描述:给定一个数据流,要求随时可以取得中位数
//定义一个大根堆和一个小根堆 首先第一个数入大根堆
public static class MinNumComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
public static class MaxNumComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
public static int findMinNum(int[] nums) {
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(new MinNumComparator());
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new MaxNumComparator());
maxHeap.add(nums[0]);
for(int i = 1; i < nums.length; i++) {
//1、当cur <= 大根堆的堆顶时 入大根堆 否则小根堆
if(nums[i] <= maxHeap.peek()) maxHeap.add(nums[i]);
else minHeap.add(nums[i]);
//2、当两个的大小不一致时 需要进行调整 谁大弹谁
if(Math.abs(maxHeap.size() - minHeap.size()) >= 2) {
if(maxHeap.size() > minHeap.size()) minHeap.add(maxHeap.poll());
else maxHeap.add(minHeap.poll());
}
}
//当长度为奇数时 则弹出长度大的那个堆顶元素
//否则 取出两个的堆顶元素作平均值
int minNum = nums.length % 2 == 1 ?
(minHeap.size() > maxHeap.size() ? minHeap.poll()
: maxHeap.poll()) : (maxHeap.poll() + minHeap.poll()) / 2;
return minNum;
}