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();
        }
  • 相关阅读:
    android: 记录及回复lisView的位置
    android获取屏幕尺寸、密度
    iphone:蓝牙传输
    android 线程 进程
    android 首次使用app时的使用教程的功能的实现
    android 启动界面
    iphone:数组的反序
    android:onKeyDown
    iphone: 可编辑的tableView Move&Delete
    iphone:类似path的抽屉式导航效果的demo总结
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4928579.html
Copyright © 2011-2022 走看看