码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Find Median from Data Stream

时间:2015-11-29 08:14:09      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

一个最大堆一个最小堆 O(1)存取 

class MedianFinder {
    Queue<Integer> min = new PriorityQueue<Integer>();
    Queue<Integer> max = new PriorityQueue<Integer>(10, 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) {
        min.offer(num);
        while (!max.isEmpty() && min.peek() < max.peek()) {
            max.offer(min.poll());
        }
        while (!max.isEmpty() && min.size() <= max.size()) {
            min.offer(max.poll());
        }
        while (!min.isEmpty() && min.size() > max.size() + 1) {
            max.offer(min.poll());
        }
    }

    // Returns the median of current data stream
    public double findMedian() {
        if (min.size() == max.size()) {
            return (min.peek() + max.peek()) / 2.0;
        } else {
            return (double)min.peek();
        }
    }
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();

 

[LeetCode]Find Median from Data Stream

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5003988.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!