如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

include "stdafx.h"

include "stdafx.h"

include

include

include

include

include

include

include

include

include

include<forward_list>

using namespace std;

class Solution {
public:
vector fl;//从小到大排序
int count = 0;
void Insert(int num)
{
auto it = fl.begin();
while (it != fl.end())
{
if (num < *it) break;
++it;
}
fl.insert(it, num); //在迭代器it前面插入一个元素
++count;
}

double GetMedian()
{
if (count % 2 == 1)
return fl[count /2];
else
return (fl[count / 2 - 1]+ fl[count / 2 ])/2.0;

}

};

int main()
{

Solution so;
cout << "[5,2,3,4,1,6,7,0,8]" << endl;
so.Insert(5);
cout << so.GetMedian() << " ";
so.Insert(2);
cout << so.GetMedian() << " ";
so.Insert(3);
cout << so.GetMedian() << " ";
so.Insert(4);
cout << so.GetMedian() << " ";
so.Insert(1);
cout << so.GetMedian() << " ";
so.Insert(6);
cout << so.GetMedian() << " ";
so.Insert(7);
cout << so.GetMedian() << " ";
so.Insert(0);
cout << so.GetMedian() << " ";
so.Insert(8);
cout << so.GetMedian() << " ";
cout << endl;

//so.getData(T);
//cout << "qu 队列中的值:" << endl;
//so.print();
//cout << endl;

return 0;
}

注意:我在做这道题的时候,是利用vector存储从小到大的元素,每次,都是取vector的中位数
此方法还有另一个解法,就是利用堆栈,效率更高,以后需要多学习。

posted @ 2016-10-26 14:56  wdan2016  阅读(929)  评论(1)    收藏  举报