zoukankan      html  css  js  c++  java
  • [LC] 295. Find Median from Data Stream

    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

    class MedianFinder {
    
        private PriorityQueue<Integer> smallPq;
        private PriorityQueue<Integer> largePq;
        /** initialize your data structure here. */
        public MedianFinder() {
            // smallPq get the max value for peek()
            smallPq = new PriorityQueue<>((a, b) -> (b - a));
            largePq = new PriorityQueue<>();
        }
        
        public void addNum(int num) {
            if (smallPq.isEmpty() || num <= smallPq.peek()) {
                smallPq.offer(num);
            } else {
                largePq.offer(num);
            }
            
            if (smallPq.size() >= largePq.size() + 2) {
                largePq.offer(smallPq.poll());
            } else if (largePq.size() > smallPq.size()) {
                smallPq.offer(largePq.poll());
            }
        }
        
        public double findMedian() {
            if (smallPq.size() == largePq.size()) {
                return (smallPq.peek() + largePq.peek()) / 2.0;
            } else {
                return (double)(smallPq.peek());
            }
        }
    }
    
    /**
     * Your MedianFinder object will be instantiated and called as such:
     * MedianFinder obj = new MedianFinder();
     * obj.addNum(num);
     * double param_2 = obj.findMedian();
     */
  • 相关阅读:
    安装jdk
    chrome
    Jenkins启动
    Red Hat Linux分辨率调整
    Jemeter第一个实例
    grep与正则表达式
    使用ngx_lua构建高并发应用
    UML建模之时序图(Sequence Diagram)
    secureCRT mac 下破解
    跨域通信的解决方案JSONP
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12015397.html
Copyright © 2011-2022 走看看