1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <iostream> #include <string> #include <vector> #include <algorithm>
using namespace std;
void InsertData(vector<int> &min, vector<int> &max,int data) { if (min.size() > max.size()) {
if (data > min[0]) { pop_heap(min.begin(), min.end(), greater<int>()); int tmp = min.back(); min.pop_back(); min.push_back(data); push_heap(min.begin(), min.end(), greater<int>()); data = tmp; }
max.push_back(data); push_heap(max.begin(), max.end(),less<int>()); } else { if (min.size() == 0) { min.push_back(data); push_heap(min.begin(), min.end(), greater<int>()); }
else { max.push_back(data); push_heap(max.begin(), max.end(), less<int>());
pop_heap(max.begin(), max.end(), less<int>()); int tmp = max.back(); max.pop_back();
min.push_back(tmp); push_heap(min.begin(), min.end(), greater<int>()); } } }
int GetMedian(vector<int> &min,vector<int> &max) {
if (min.size() + max.size() == 0) { cout << "无元素" << endl; return -1; }
if ((min.size() + max.size()) & 1) { return min[0]; } else { return (min[0] + max[0]) / 2; }
return 0; }
int main() {
vector<int> min; vector<int> max;
vector<int> nums = { 1,2,3,4,5,6 }; vector<int> nums1 = { 1,2,3,4,5,6,7 };
for (auto i : nums1) { InsertData(min, max, i); }
cout << GetMedian(min, max) << endl;
return 0; }
|