您的位置:首页 > 编程语言 > Java开发

[LeetCode][Java]Find Median from Data Stream

2015-11-01 21:03 429 查看

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

https://leetcode.com/problems/find-median-from-data-stream/

找出中位数,暴力O(n^2)超时。

O(nlogn)的做法是开两个堆(java用优先队列代替)。

最小堆放小于中位数的一半,最大堆放较大的另一半。

addNum操作,把当前的num放到size小的堆中,通过2次poll-add操作,保证了最小堆中的所有数都小于最大堆中的数。

findMedian操作,如果size不同,就是其中一个堆顶,否则就是连个堆顶的数相加除以2。

class MedianFinder {

private Queue<Integer> max = new PriorityQueue<Integer>(Collections.reverseOrder());
private Queue<Integer> min = new PriorityQueue<Integer>();

// Adds a number into the data structure.
public void addNum(int num) {
if(max.size() < min.size()){
max.add(num);
min.add(max.poll());
max.add(min.poll());
}else{
min.add(num);
max.add(min.poll());
min.add(max.poll());
}
}

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


上面的做法,有多余的poll-add操作,可以做些优化。

// Adds a number into the data structure.
public void addNum(int num) {
max.add(num);
min.add(max.poll());
if(max.size() < min.size()){
max.add(min.poll());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: