题解 | #数据流中的中位数#
数据流中的中位数
https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1
import java.util.*;
public class Solution {
//定义一个数组存放排序的结果
ArrayList<Integer> val=new ArrayList<Integer>();
public void Insert(Integer num) {
//定义一个数组存放排序的结果
int i=0;
//遍历数组,插入num,对于每一个num都需要遍历,所有i=0;
for(;i<val.size();i++){
if(num>val.get(i)){
break;
}
}
//特别注意这个是在for循环外的
val.add(i,num);
}
public Double GetMedian() {
int n=val.size();
//中位数计算,当数组的个数为奇数时
double res;
if (n%2==1){
res=val.get(n/2);
}else{
double a=val.get(n/2);
double b=val.get((n/2)-1);
res=(a+b)/2;
}
return res;
}
}
