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

数据流中的中位数

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

import java.util.*;


public class Solution {

    public PriorityQueue<Integer> stream = new PriorityQueue<>();

    public void Insert(Integer num) {
        stream.add(num);
    }

    public Double GetMedian() {
        // 1.将公共堆复制到临时堆
        PriorityQueue<Integer> temp = new PriorityQueue<>(stream);

        // 2.计算堆的size与奇偶
        int size = temp.size();
        if (size == 0) {
            return 0.0;
        }
        int count = size / 2;
        if (size % 2 == 0) {
            count--;
        }

        // 3.依次从堆中弹出元素,找到或计算出中位数
        double cur = 0.0;
        while (count-- >= 0) {
            cur = temp.poll();
        }

        if (size % 2 == 0) {
            cur = (cur + temp.poll()) / 2;
        }

        return cur;
    }


}

全部评论

相关推荐

ResourceUtilization:四六级不愧是大学最有用的证之一
点赞 评论 收藏
分享
03-30 19:30
石家庄学院 Java
野蛮的柯基在游泳:都能入股了,还得是Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务