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
  • 相关阅读:
    Session攻击(会话劫持+固定)与防御
    console调试命令
    javascript获取当前url
    搞不清FastCgi与PHP-fpm之间是个什么样的关系
    MySQL基本语句优化10个原则
    PHP获取类名及所有函数名
    js闭包
    字段、方法、属性
    python面向对象之类成员修饰符
    实现Python代码发送邮件
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13665325.html
Copyright © 2011-2022 走看看