每次添加一个数进入List数组,然后对数组进行排序,在计算中位数。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
List<Integer> list = new ArrayList<>();
public void Insert(Integer num) {
list.add(num);
Collections.sort(list);
}
public Double GetMedian() {
int len = list.size();
int mid = len / 2;
return len % 2 == 0 ? (double) (list.get(mid - 1) + list.get(mid)) / 2: (double) (list.get((len - 1) / 2));
}
}