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();
        }
  • 相关阅读:
    计算机术语
    【转】 物理内存和线性空间
    windows Visual Studio 上安装 CUDA【转载】
    windows Notepad++ 上配置 vs 编译器 , 编译并运行
    单列模式 [转载]
    Java Swing布局管理器GridBagLayout的使用示例 [转]
    五年java工作应具备的技能
    三年java软件工程师应有的技技能
    京东面试题 Java相关
    京东笔试题总结
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4928579.html
Copyright © 2011-2022 走看看