数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。
中位数的定义:
中位数是排序后数组的中间值,如果有数组中有n个数,则中位数为A[(n-1)/2]。
比如:数组A=[1,2,3]的中位数是2,数组A=[1,19]的中位数是1。
样例
持续进入数组的数的列表为:[1, 2, 3, 4, 5],则返回[1, 1, 2, 2, 3]
中位数的定义:
中位数是排序后数组的中间值,如果有数组中有n个数,则中位数为A[(n-1)/2]。
比如:数组A=[1,2,3]的中位数是2,数组A=[1,19]的中位数是1。
样例
持续进入数组的数的列表为:[1, 2, 3, 4, 5],则返回[1, 1, 2, 2, 3]
时间复杂度为O(nlogn)
private PriorityQueue<Integer> minheap, maxheap;
private int numOfElement = 0;
public int[] medianII(int[] nums) {
Comparator <Integer> rev = new Comparator/*<>*/<Integer>(){
@Override
public int compare(Integer left, Integer right){
return right.compareTo(left);
}
};
int count = nums.length;
maxheap = new PriorityQueue<Integer>(count, rev);
minheap = new PriorityQueue<Integer>(count);
int []ans = new int[count];
for(int i=0; i<count; i++){
addNumber(nums[i]);
ans[i]=getMedian();
}
return ans;
}
public void addNumber(int k){
maxheap.offer(k);
if(numOfElement % 2==0){
if(minheap.size()== 0){
numOfElement++;
return;
}else if(maxheap.peek() > minheap.peek()){
Integer max = maxheap.poll();
Integer min = minheap.poll();
maxheap.offer(min);
minheap.offer(max);
}
}else{
minheap.offer(maxheap.poll());
}
numOfElement++;
}
public int getMedian(){
return maxheap.peek();
}