试题编号: | 201612-1 |
试题名称: | 中间数 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 在一个整数序列a1, a2, …, an中,如果存在某个数,大于它的整数数量等于小于它的整数数量,则称其为中间数。在一个序列中,可能存在多个下标不相同的中间数,这些中间数的值是相同的。 输入格式 输入的第一行包含了一个整数n,表示整数序列中数的个数。 输出格式 如果约定序列的中间数存在,则输出中间数的值,否则输出-1表示不存在中间数。 样例输入 6 样例输出 5 样例说明 比5小的数有2个,比5大的数也有2个。 样例输入 4 样例输出 -1 样例说明 在序列中的4个数都不满足中间数的定义。 样例输入 5 样例输出 -1 样例说明 在序列中的5个数都不满足中间数的定义。 评测用例规模与约定 对于所有评测用例,1 ≤ n ≤ 1000,1 ≤ ai ≤ 1000。 |
用map排序,判断前半部分等于后半部分的数量就说明存在中间数,值得注意的是当输入都为相同值时,前后数量都为0也相等,同样存在中间数。
#include <map>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <time.h>
#include <vector>
#include <list>
using namespace std;
int main()
{
int i, j, N, num;
cin >> N ; //
map<int, int>Data;
for (i = 0; i < N; i++)
{
cin >> num;
Data[num] ++;
}
int Sum = 0;
bool flag = 0;
for (map<int, int>::iterator it = Data.begin(); it != Data.end();)
{
if ((*it).second == N)
{
cout << (*it).first;
flag = 1;
break;
}
else if ((Sum + (*it).second) > (N - 1) / 2)
{
cout << -1;
flag = 1;
break;
}
else
Sum += (*it).second;
if ((++it) != Data.end() && Sum == (N - Sum - (*it).second))
{
flag = 1;
cout << (*it).first;
break;
}
}
if (flag == 0)
cout << -1;
cin >> N;
return 0;
}