描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
数据范围:数据流中数个数满足 ,大小满足
进阶: 空间复杂度 , 时间复杂度
示例1
输入[5,2,3,4,1,6,7,0,8]
返回值:"5.00 3.50 3.00 3.50 3.00 3.50 4.00 3.50 4.00 "
说明:
数据流里面不断吐出的是5,2,3...,则得到的平均数分别为5,(5+2)/2,3...
示例2
输入:[1,1,1]
返回值:"1.00 1.00 1.00 "
第一种方法
定义两个变量,一个为list,存储所有数据,一个为总个数,代码如下
int count = 0;
List<Integer> list = new ArrayList<>();
public void firstInsert(Integer num) {
list.add(num);
}
public Double firstGetMedian() {
count++;
if(count%2 != 0){
return list.get(count/2)*1.0;
}else {
Collections.sort(list);
int i = count/2;
return (list.get(i) + list.get(i-1))/2*1.0;
}
}
第二种方法
采用两个堆来解决,大堆存较大数据,小堆存较小数据。
int count = 0;
PriorityQueue<Integer> max = new PriorityQueue<>((o1,o2) -> o2-o1);
PriorityQueue<Integer> min = new PriorityQueue<>();
public void secondInsert(Integer num) {
count++;
if(count % 2 != 0){
max.add(num);
min.add(max.poll());
}else {
min.add(num);
max.add(min.poll());
}
}
public Double secondGetMedian() {
if(count%2 != 0){
return new Double(min.peek());
}else {
return (min.peek() + max.peek())/2.0;
}
}