LeetCode-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:
addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2
解题思路:可以利用priority_queue来解决,建立两个堆,一个最大堆max_heap和一个最小堆min_heap,使得最大堆中存放的是较小的元素,而最小堆中存放的是较大的元素,因此要将最大的top()元素压入最小堆,同时要两个堆的元素个数要保持平衡
lass MedianFinder
{
public:
void addNum(int num)
{
max_heap.push(num);
min_heap.push(max_heap.top());
max_heap.pop();
if (max_heap.size() < min_heap.size())
{
max_heap.push(min_heap.top());
min_heap.pop();
}
}
double findMedian()
{
return max_heap.size() > min_heap.size() ? (double)max_heap.top() : (max_heap.top() + min_heap.top())*0.5;
}
private:
priority_queue<int> max_heap;
priority_queue<int, vector<int>, greater<int>> min_heap;
};