[LeetCode]Find Median from Data Stream

一个最大堆一个最小堆 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();

 

posted @ 2015-11-29 07:43  Weizheng_Love_Coding  阅读(141)  评论(0编辑  收藏  举报