题解 | 数据流中的中位数

数据流中的中位数

https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1

import java.util.*;


public class Solution {

    ArrayList<Integer> list = new ArrayList<>();

    public void Insert(Integer num) {
        // list中没有元素,直接插入
        if (list.isEmpty()) {
            list.add(num);
        } else {
            int i = 0;
            // 遍历找到插入点
            for (; i < list.size(); i ++) {
                if (num <= list.get(i)) break;
            }
            // 插入相应的位置
            list.add(i, num);
        }
    }

    public Double GetMedian() {
        int size = list.size();
        // 奇数个数字
        if (size % 2 == 1) {
            return (double) list.get(size / 2);
        } else {
            int midIndex1 = size / 2 - 1;
            int midIndex2 = size / 2;
            return (list.get(midIndex1) + list.get(midIndex2)) / 2.0;
        }
    }


}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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