295. Find Median from Data Stream***

来源:互联网 发布:网络成瘾的影响 编辑:程序博客网 时间:2024/05/20 05:06

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
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做,随时插入。两次比较是为了保证新加入的元素和前半部分和后半部分都要比较,而不是一半。
0 0
原创粉丝点击