1 package offer; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值, 8 * 那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值, 9 * 那么中位数就是所有数值排序之后中间两个数的平均值。 10 * 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 11 * @author 爱不会绝迹 12 * 13 */ 14 public class Problem39 { 15 static List<Integer> list = new ArrayList<>(); 16 public static void Insert(Integer num) { 17 list.add(num); 18 } 19 20 public static Double GetMedian() { 21 int len = list.size(); 22 list.sort((x,y)->x-y); 23 if(len%2!=0){ 24 return (double)list.get((len/2)); 25 }else{ 26 return (double)(list.get((len/2)-1) + list.get((len/2)))/2; 27 } 28 } 29 30 public static void main(String[] args) { 31 Insert(1); 32 Insert(2); 33 Insert(3); 34 Insert(4); 35 Insert(5); 36 Insert(6); 37 38 System.out.println(GetMedian()); 39 40 } 41 }