方法一:排序取中位数(超时)
class MedianFinder {
public:
/** initialize your data structure here. */
vector<int> record;
MedianFinder() {
}
void addNum(int num) {
record.push_back(num);
}
double findMedian() {
double result = 0;
if( record.size() == 0 )
return result;
sort( record.begin(), record.end() );
//奇数
if( record.size() & 1 )
{
result = record[ record.size() / 2 ];
}
else
{
result = (double)( record[ record.size() / 2 - 1 ] + record[ record.size() / 2 ] ) / 2;
}
return result;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
方法二:大、小堆实现
1.通过两个堆,一个最大堆一个最小堆,大小不超过1 ,如果超过1就把大小堆平衡一下
2.中位数如果是奇数则为最大堆的top或最小堆的top,如果最大堆和最小堆的大小相等,则取两个堆顶的平均值
3.最小堆里面的数据都要比最大堆大
class MedianFinder {
public:
/** initialize your data structure here. */
//最大堆
priority_queue< int, vector<int> > max_heap;
//最小堆
priority_queue< int, vector<int>, greater<int> > min_heap;
MedianFinder() {
}
void addNum(int num) {
if( max_heap.empty() || num < max_heap.top() )
{
max_heap.push( num );
}
else
min_heap.push( num );
//维持堆得大小
if( max_heap.size() == min_heap.size() + 2)
{
min_heap.push(max_heap.top());
max_heap.pop();
}
else if( min_heap.size() == max_heap.size() + 2)
{
max_heap.push( min_heap.top() );
min_heap.pop();
}
}
double findMedian() {
if( ( max_heap.size() + min_heap.size() ) == 0 )
return -1;
if( max_heap.size() > min_heap.size() )
{
return max_heap.top();
}
else if( max_heap.size() < min_heap.size() )
{
return min_heap.top();
}
else
return double( max_heap.top() + min_heap.top() ) / 2;
}
};