您的位置:首页 > 其它

295. Find Median from Data Stream***

2017-02-26 18:36 288 查看
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.5
addNum(3)
findMedian() -> 2

class MedianFinder {

private Queue<Long> small = new PriorityQueue(),
large = new PriorityQueue();

public void addNum(int num) {
large.add((long) num);
small.add(-large.poll());
if (large.size() < small.size())
large.add(-small.poll());
}

public double findMedian() {
return large.size() > small.size()
? large.peek()
: (large.peek() - small.peek()) / 2.0;
}
};
总结:机智哭了,不过可以用binarysearch做,随时插入。两次比较是为了保证新加入的元素和前半部分和后半部分都要比较,而不是一半。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: