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();
     */
  • 相关阅读:
    Windows下使用CMake编译SuiteSparse成VS工程
    【设计模式
    【设计模式
    vue过滤和复杂过滤
    el-tooltip 自定义样式
    el-table加表单验证
    使用Go env命令设置Go的环境
    面试官:GET 和 POST 两种基本请求方法有什么区别?
    解决 Vue 重复点击相同路由报错的问题
    利用promise和装饰器封装一个缓存api请求的装饰器工具
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12015397.html
Copyright © 2011-2022 走看看