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)
findMedian() -> 1.5
findMedian() -> 2
``````

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

``````class MedianFinder {
public:

// Adds a number into the data structure.
small.push(num);
large.push(-small.top());
small.pop();
if (small.size() < large.size()) {
small.push(-large.top());
large.pop();
}
}

// Returns the median of current data stream
double findMedian() {
return small.size() > large.size() ? small.top() : 0.5 *(small.top() - large.top());
}

private:
priority_queue<long> small, large;
};
``````

``````class MedianFinder {
public:

// Adds a number into the data structure.
small.insert(num);
large.insert(-*small.begin());
small.erase(small.begin());
if (small.size() < large.size()) {
small.insert(-*large.begin());
large.erase(large.begin());
}
}

// Returns the median of current data stream
double findMedian() {
return small.size() > large.size() ? *small.begin() : 0.5 * (*small.begin() - *large.begin());
}

private:
multiset<long> small, large;
};
``````

https://leetcode.com/discuss/64850/short-simple-java-c-python-o-log-n-o-1

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation