题目描述
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
class DynamicArray{
public:
void Insert(int num)
{
if (((min.size() + max.size()) & 1) == 0)
{
if(max.size() > 0 && num < max[0])
{
max.push_back(num);
push_heap(max.begin(),max.end(),less<int>());
num = max[0];
pop_heap(max.begin(), max.end(), less<int>());
max.pop_back();
}
min.push_back(num);
push_heap(min.begin(), min.end(), greater<int>());
}
else
{
if(min.size() > 0 && num > min[0])
{
min.push_back(num);
push_heap(min.begin(), min.end(), greater<int>());
num=min[0];
pop_heap(min.begin(), min.end(), greater<int>());
min.pop_back();
}
max.push_back(num); //把后一半找到的最大值放到前一半中
push_heap(max.begin(), max.end(), less<int>());
}
}
double GetMedian()
{
int size = min.size() + max.size();
if(size == 0)
throw exception("No numbers are availeable");
double median = 0;
if((size&1) != 0) {
median = (double) min[0]; //这里一定要注意强制转换,否则就会出错
} else {
median = (double) (max[0] + min[0]) / 2;
}
return median;
}
private:
vector<int> min;
vector<int> max;
};
void Test(char* testName, DynamicArray &numbers, double expected)
{
if(testName != NULL)
printf("%s begins: ", testName);
if(abs(numbers.GetMedian() - expected) < 0.0000001)
printf("Passed.\n");
else
printf("FAILED.\n");
}
int main(int argc, char* argv[])
{
DynamicArray numbers;
printf("Test1 begins: ");
try
{
numbers.GetMedian();
printf("FAILED.\n");
}
catch(exception e)
{
printf("Passed.\n");
}
numbers.Insert(5);
Test("Test2", numbers, 5);
numbers.Insert(2);
Test("Test3", numbers, 3.5);
numbers.Insert(3);
Test("Test4", numbers, 3);
numbers.Insert(4);
Test("Test6", numbers, 3.5);
numbers.Insert(1);
Test("Test5", numbers, 3);
numbers.Insert(6);
Test("Test7", numbers, 3.5);
numbers.Insert(7);
Test("Test8", numbers, 4);
numbers.Insert(0);
Test("Test9", numbers, 3.5);
numbers.Insert(8);
Test("Test10", numbers, 4);
return 0;
}