import java.util.Comparator;
import java.util.PriorityQueue;
//生成小根堆的比较器
class MinHeapComparator1 implements Comparator<Integer> {
@Override
public int compare(Integer o1,Integer o2){
return o1-o2;
}
}
//生成大根堆的比较器
class MaxHeapComparator1 implements Comparator<Integer>{
@Override
public int compare(Integer o1,Integer o2){
return o2-o1;
}
}
//
class MedianHolder1{
//成员变量 attribute(属性)
private PriorityQueue<Integer> minHeap;
private PriorityQueue<Integer> maxHeap;
//构造器 Holder(持有者)
public MedianHolder1(){
this.minHeap=new PriorityQueue<Integer>(new MinHeapComparator1());
this.maxHeap=new PriorityQueue<Integer>(new MaxHeapComparator1());
}
//数据进流
public void addNum(int num){
if(maxHeap.isEmpty()||num<=maxHeap.peek()){
maxHeap.add(num);
} else{
minHeap.add(num);
}
modifyTowHeap1();
}
//求中位数
public int getMedian(){
if(maxHeap.isEmpty()){
return -1;
}
if(this.minHeap.size()==this.maxHeap.size()){
return (this.maxHeap.peek()+this.minHeap.peek())/2;
}else{
return this.maxHeap.size()>this.minHeap.size()?this.maxHeap.peek():this.minHeap.peek();
}
}
public void print(){
while(!this.maxHeap.isEmpty()){
System.out.print(this.maxHeap.poll()+" ");
}
while(!this.minHeap.isEmpty()){
System.out.println(this.minHeap.poll()+" ");
}
}
//调整两个堆
//策略:两个之间的数量不能超过2个元素
private void modifyTowHeap1(){
if(this.maxHeap.size()==this.minHeap.size()+2){
//如果小根堆的数量比大根堆的数量超过2,就把小根堆的堆顶元素放到大根堆中
this.maxHeap.add(this.minHeap.poll());
}
if(this.minHeap.size()==this.maxHeap.size()+2){
this.minHeap.add(this.maxHeap.poll());
}
}
}
//求流中的中位数
public class Test14 {
public static void main(String[] args) {
MedianHolder1 medianHolder1=new MedianHolder1();
medianHolder1.addNum(1);
medianHolder1.addNum(2);
medianHolder1.addNum(3);
medianHolder1.addNum(4);
int median=medianHolder1.getMedian();
System.out.println(median);
}
}