题解 | 数据流中的中位数

数据流中的中位数

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;
        }
    }


}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 14:00
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务