题解 | 数据流中的中位数
数据流中的中位数
https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1
import java.util.*; public class Solution { // 使用链表来保存数据流,添加一个元素之后就对链表进行排序 ArrayList<Integer> list = new ArrayList<>(); public void Insert(Integer num) { list.add(num); Collections.sort(list); } // 如果当前数据流是奇数个数,中位数就是排序后位于中间的数值 // 如果当前数据流是偶数个数,中位数就是排序后中间两个数的平均值 public Double GetMedian() { int len = list.size(); if(len % 2 == 1){ int mid = len / 2; return list.get(mid) / 1.0; }else{ int mid = len / 2; int num1 = list.get(mid - 1); int num2 = list.get(mid); return (num1 + num2) / 2.0; } } }