您的位置:首页 > 其它

Find Median from Data Stream

2016-07-21 02:46 267 查看
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


分析:
使用两个heap,一个min heap(root的值最小) and max heap (root的值最大)。保持两个heap的size差别最大为1, 而且maxHeap的size不能比minHeap的size 小。

public class MedianFinder {

PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
return y - x;
}
});

public static void main(String[] args) {
MedianFinder mf = new MedianFinder();
mf.addNum(2);
mf.addNum(3);
System.out.println(mf.findMedian());
}

// Adds a number into the data structure.
public void addNum(int num) {
if (maxHeap.isEmpty()) {
maxHeap.offer(num);
return;
}

if (num < maxHeap.peek()) {
maxHeap.offer(num);
} else {
minHeap.offer(num);
}

if (maxHeap.size() > minHeap.size() + 1) {
minHeap.offer(maxHeap.poll());
} else if (maxHeap.size() < minHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}

// Returns the median of current data stream
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else {
return maxHeap.peek();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: