zoukankan      html  css  js  c++  java
  • 295. Find Median from Data Stream 295.从数据流中查找中位数

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

    For example,

    [2,3,4], the median is 3

    [2,3], the median is (2 + 3) / 2 = 2.5

    Design a data structure that supports the following two operations:

    • void addNum(int num) - Add an integer number from the data stream to the data structure.
    • double findMedian() - Return the median of all elements so far.

    思路:觉得没有必要啊,为什么要用Q?大概就是免除了:算中位数还要除以2加1减1之类的烦恼。体会一下Q在排序时的优越性

    排队Q领offer,所以动词应该是offer

    class MedianFinder {
        PriorityQueue<Integer> min;
        PriorityQueue<Integer> max;
    
        /** initialize your data structure here. */
        public MedianFinder() {
            min = new PriorityQueue<Integer>();
            max = new PriorityQueue<Integer>(1000,
                                     Collections.reverseOrder());
        }
        
        public void addNum(int num) {
            max.offer(num);
            min.offer(max.poll());
            
            if (max.size() < min.size()) {
                max.offer(min.poll());
            }
        }
        
        public double findMedian() {
            if (min.size() == max.size()) 
                return (min.peek() + max.peek()) / 2.0;
            else 
                return max.peek();
        }
    }
    View Code
  • 相关阅读:
    【C++ 系列笔记】03 C++ 面向对象进阶
    【C++ 系列笔记】02 C++ 面向对象基础
    【C++ 系列笔记】01 C++ 与 C
    【JavaScript】简单取随机数 ~~(Math.random() * number)
    英语测试
    Linux指令入门
    RE-攻防世界 T3 insanity
    PWN-攻防世界 level0
    ISCC不会的理论题
    kali linux配置ssh
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13665325.html
Copyright © 2011-2022 走看看