zoukankan      html  css  js  c++  java
  • [leetcode] 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.
    
    Examples: 
    [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.
    For example:
    
    add(1)
    add(2)
    findMedian() -> 1.5
    add(3) 
    findMedian() -> 2

    分析:维护一个大顶堆(maxHeap)和一个小顶堆(minHeap),其中大顶堆的元素都小于小顶堆的元素,比如add 2, 3, 4, 5, 6后,堆内的元素如下:

    maxHeap
    4
    3
    2
    minHeap
    5
    6

    当maxHeap.size() != minHeap.size()时,返回maxHeap.peek();当maxHeap.size() == minHeap.size()时,返回(maxHeap.peek() + minHeap.peek())/2.

    Java代码如下:

        PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            };
        });
        // Adds a number into the data structure.
        public void addNum(int num) {
            maxHeap.offer(num);
            minHeap.offer(maxHeap.poll());
            if (maxHeap.size() < minHeap.size()) {
                maxHeap.offer(minHeap.poll());
            }
        }
    
        // Returns the median of current data stream
        public double findMedian() {
            return maxHeap.size() == minHeap.size() ? (double)(maxHeap.peek()+minHeap.peek())/2 : maxHeap.peek();
        }
  • 相关阅读:
    如何基于Azure平台实现MySQL HA(方法论篇)
    如何对Azure磁盘性能进行测试
    Azure底层架构的初步分析
    聊聊Azure的安全性
    关于Azure带宽的测试
    JavaScript 优化
    SQL时间段查询
    win7+64位+Oracle+11g+64位下使用PLSQL+Developer+的解决办法
    putty 使用方法,中文教程
    怎样才能专心工作
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4928579.html
Copyright © 2011-2022 走看看