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 a integer number from the data stream to the data structure.
    • double findMedian() - Return the median of all elements so far.

     

    Example:

    addNum(1)
    addNum(2)
    findMedian() -> 1.5
    addNum(3) 
    findMedian() -> 2

    思路:忘了是怎么最小值都存maxQ,最大值都存minQ的了。原来是:min中存的是max中poll出来的东西

    没必要取出来 只是看一看的话,用peek()就行了。poll()是“获取并删除”

    class MedianFinder {
        PriorityQueue<Integer> maxQ;
        PriorityQueue<Integer> minQ;
    
        /** initialize your data structure here. */
        public MedianFinder() {
            maxQ = new PriorityQueue<Integer>();
            //得这么写
            minQ = new PriorityQueue<Integer>(1000, Collections.reverseOrder());
        }
        
        public void addNum(int num) {
            maxQ.offer(num);
            minQ.offer(maxQ.poll());
            
            if (maxQ.size() < minQ.size()) {
                maxQ.offer(minQ.poll());
            }
        }
        
        public double findMedian() {
            if (maxQ.size() == minQ.size()) {
                return (maxQ.peek() + minQ.peek()) / 2.0;
            }else {
                return maxQ.peek();
            }
        }
    }
    
    /**
     * Your MedianFinder object will be instantiated and called as such:
     * MedianFinder obj = new MedianFinder();
     * obj.addNum(num);
     * double param_2 = obj.findMedian();
     */
    View Code
    
    
    
     
  • 相关阅读:
    Selenium—浏览器相关操作
    Selenium—对话框处理
    Selenium—获取页面的title,url;使用句柄方式切换窗口
    Jmeter安装及配置(傻瓜模式)
    面试宝典(二)
    Python-接口自动化(十一)
    Jmeter启动报错解决方案
    Python-接口自动化(十)
    Python-接口自动化(九)
    Mac上实现Python用HTMLTestRunner生成html测试报告
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13738285.html
Copyright © 2011-2022 走看看