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

数据流中的中位数

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

import java.util.* ;
public class Solution {
    //小-》大
    PriorityQueue<Integer> p1 = new PriorityQueue<>() ;
    //大-》小
    PriorityQueue<Integer> p2 = new PriorityQueue<>(new Comparator<Integer>(){
        public int compare(Integer i1 , Integer i2) {
            return i2 - i1 ;
        }
    }) ;
    public void Insert(Integer num) {
        //先进小顶堆再进大顶堆保证了大顶堆的最小值都大于小顶堆的最大值
        p1.offer(num) ;
        p2.offer(p1.poll()) ;
        if(p2.size() - p1.size() > 1) {
            p1.offer(p2.poll()) ;
        }
    }

    public Double GetMedian() {
        if(p2.size() > p1.size()) {
            return p2.peek()*1.0 ;
        } else {
            return (0.0 + p1.peek() + p2.peek())/2 ;
        }
    }


}

一个菜鸟的算法刷题记录 文章被收录于专栏

分享一个菜鸟的成长记录

全部评论

相关推荐

11-03 13:18
门头沟学院 Java
包行:平时怎么刷算法题的哇,字节的手撕听说都很难
字节跳动工作体验
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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