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();
     */
  • 相关阅读:
    关于医学的一点想法
    我的ArcGis9.3 到Arcgis10.0 升级步骤
    最近一月的娱乐生活:看电影,玩游戏
    最近一月的娱乐生活:看电影,玩游戏
    5年技术学习历程的回顾
    5年技术学习历程的回顾
    网站开发的技术选型问题
    网站开发的技术选型问题
    学技术真累
    Java实现 LeetCode 200 岛屿数量
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12015397.html
Copyright © 2011-2022 走看看