// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<list>
#include<iterator>
#include<queue>
#include<stack>
#include<algorithm>
#include<forward_list>
using namespace std;
class Solution {
public:
vector <int> 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的中位数
此方法还有另一个解法,就是利用堆栈,效率更高,以后需要多学习。