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

数据流中的中位数

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


}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-28 12:15
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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