[hard]295. Find Median from Data Stream

来源:互联网 发布:大数据的关键技术 编辑:程序博客网 时间:2024/05/04 05:57

295. 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.5add(3) findMedian() -> 2

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

Solution:

It's a super classic problem, maintain two heaps. view codes to see my tricks.


class MedianFinder {private:    priority_queue <int> tail_half;    priority_queue <int, vector <int>, greater<int> > head_half;public:    // Adds a number into the data structure.    void addNum(int num) {        tail_half.push(num);        head_half.push(tail_half.top());        tail_half.pop();        if (head_half.size() > tail_half.size()) {            tail_half.push(head_half.top());            head_half.pop();        }    }    // Returns the median of current data stream    double findMedian() {        size_t size = head_half.size() + tail_half.size();        if (size & 1)            return tail_half.top();        return (head_half.top() + tail_half.top()) / 2.0;    }};


0 0
原创粉丝点击