295. Find Median from Data Stream

来源:互联网 发布:阿尔法算法 编辑:程序博客网 时间:2024/06/05 23:50

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:

addNum(1)addNum(2)findMedian() -> 1.5addNum(3) findMedian() -> 2

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

这里需要维护两个堆,一个minheap和maxheap。先把数放进maxheap,排好序之后把顶端的元素放进minheap,这时如果minheap比maxheap的长度大2以上,把minheap顶端的元素放进minheap保持两个heap平衡。返回时如果两个heap的长度相同,返回两个heap顶端元素的平均,不同,返回maxheap的顶端元素。代码如下:

public class MedianFinder {    PriorityQueue<Double> maxHeap;    PriorityQueue<Double> minHeap;    /** initialize your data structure here. */    public MedianFinder() {        maxHeap = new PriorityQueue<Double>();        minHeap = new PriorityQueue<Double>();    }        public void addNum(int num) {        minHeap.add((double)num);        maxHeap.add(-minHeap.poll());        if (maxHeap.size() > minHeap.size() + 1) {            minHeap.add((double)-maxHeap.poll());        }    }        public double findMedian() {        return minHeap.size() == maxHeap.size()? (minHeap.peek() - maxHeap.peek()) / 2: -maxHeap.peek();    }}/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */

原创粉丝点击