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();
     */
  • 相关阅读:
    4.22课堂
    4.21课堂
    4.20作业
    4.20课堂
    4.17课堂
    4.16课堂
    4.15作业
    4.15反射与内置方法
    4.10绑定与非绑定
    70、django中间件
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12015397.html
Copyright © 2011-2022 走看看