一、题目
二、解析
由题可知,若中间数存在,则它一定在输入序列的正中间。
使用vector容器保存输入的序列并用sort排序(见博客:CCF 201903-1 小中大【使用vector容器排序】),然后使用两个iterator:front和back,从序列的中间分别向前/向后遍历,根据情况分类讨论。
三、代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<int> v;
struct cmp {
bool operator() (int d1, int d2)
{
return d1 < d2;
}
};
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
v.push_back(num);
}
sort(v.begin(), v.end(), cmp());
/*for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
cout << *it << " ";
cout << endl;*/
vector<int>::iterator front;
vector<int>::iterator back;
if (n % 2 == 0) {
front = v.begin() + n / 2 - 1;
back = v.begin() + n / 2;
}
else {
front = v.begin() + n / 2;
back = v.begin() + n / 2;
}
//cout<<*front<<" "<<*back<<endl;
if (*front != *back)
cout << "-1" << endl;
else {
int mid = *front;
while (front != v.begin() & back != (v.end() - 1) & *front == *back) {
front -= 1;
back += 1;
}
if (*front != *back) {
if (*front == mid | *back == mid)
cout << "-1" << endl;
else
cout << mid << endl;
}
else
cout << mid << endl;
}
return 0;
}
输入:
6
2 6 5 6 3 5
输出:
5