题解 | #数据流中的中位数#

数据流中的中位数

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

思路

使用插入排序思路对数据流进行不断的排序,详细参考官方思路

代码

import java.util.*;

public class Solution {

    List<Integer> nums = new ArrayList<>();

    /**
     * 数据流读取方法
     *
     * @param num 数据
     * @apiNote
     * @since 2023/1/14 13:45
     */
    public void Insert(Integer num) {
        if (nums.isEmpty()) {
            // 将数据加入集合中
            nums.add(num);
        } else {
            // 让集合有序
            int index = 0;
            // 寻找插入点
            for (; index < nums.size(); index++) {
                if (num <= nums.get(index)) {
                    break;
                }
            }
            // 将数据插入相应位置
            nums.add(index, num);
        }
    }

    public Double GetMedian() {
        // 计算当前集合大小
        int length = nums.size();
        // 如果为奇数
        if (length % 2 == 1) {
            return Double.valueOf(nums.get(length / 2 ));
        } else {
            // 如果是偶数
            return (nums.get(length / 2).doubleValue() + nums.get(length / 2 - 1).doubleValue()) / 2;
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务