试题编号: 201612-1
试题名称: 中间数
时间限制: 1.0s
内存限制: 256.0MB
问题描述:
问题描述
在一个整数序列a1, a2, …, an中,如果存在某个数,大于它的整数数量等于小于它的整数数量,则称其为中间数。在一个序列中,可能存在多个下标不相同的中间数,这些中间数的值是相同的。
给定一个整数序列,请找出这个整数序列的中间数的值。
输入格式
输入的第一行包含了一个整数n,表示整数序列中数的个数。
第二行包含n个正整数,依次表示a1, a2, …, an。
输出格式
如果约定序列的中间数存在,则输出中间数的值,否则输出-1表示不存在中间数。
样例输入
6
2 6 5 6 3 5
样例输出
5
样例说明
比5小的数有2个,比5大的数也有2个。
样例输入
4
3 4 6 7
样例输出
-1
样例说明
在序列中的4个数都不满足中间数的定义。
样例输入
5
3 4 6 6 7
样例输出
-1
样例说明
在序列中的5个数都不满足中间数的定义。
评测用例规模与约定
对于所有评测用例,1 ≤ n ≤ 1000,1 ≤ ai ≤ 1000。
题目解析:
注意只有一种数的时候,他就是中间数,详细可看代码
代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
//直接统计 , 下面方法是运行时比较。
//直接统计时,一定注意只有一种数的时候,他就是中间数
int main(){
int n , number;
map<int, int> mp;
vector<pair<int,int>> vc;
while(cin >> n){
for(int i = 0; i < n ; i++){
cin >> number;
mp[number]++;
}
map<int,int>::iterator it = mp.begin();
for(it ; it != mp.end(); it++){
vc.push_back(make_pair(it->first,it->second));
}
bool flag = false;
for(int i = 1; i < vc.size() - 1 ; i++){
//查该数的左边
int left = 0;
for(int j = 0 ; j < i ; j++){
left += vc[j].second;
}
//查该数的右边
int right = 0;
for(int j = i + 1; j < vc.size(); j++){
right += vc[j].second;
}
if(left == right){
flag = true;
cout << vc[i].first << endl;
break;
}
}
if(flag == false){
if(vc.size() == 1){
cout << vc[0].first << endl;
}else{
cout << -1 << endl;
}
}
vc.clear();
mp.clear();
}
return 0;
}
/* 测试用例
6
2 6 5 6 3 5
4
3 4 6 7
5
3 4 6 6 7
*/
/* 运行时比较
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main(){
int n , number;
map<int, int> mp;
vector<pair<int,int>> vc;
while(cin >> n){
for(int i = 0; i < n ; i++){
cin >> number;
mp[number]++;
}
//找出中间数 , 当出现中间数的时候,一定是在中间,所以用mid比较
int ans , mid = (n + 1) / 2 , count = 0 , left;
map<int,int>::iterator it = mp.begin();
for(it ; it != mp.end(); it++){
if(count + it->second >= mid){ //累计超过了mid
left = count; //左边的数目
count = 0;
ans = it->first;
}else{ //累计数目
count += it->second;
}
}
if(count == left){
cout << ans << endl;
}else{
cout << -1 << endl;
}
mp.clear();
}
return 0;
}
*/
本文介绍了一种算法,用于在一个整数序列中找到中间数,即数值两边整数数量相等的数。通过统计每个数出现的次数并进行比较,算法能够有效找出中间数或判断其是否存在。

被折叠的 条评论
为什么被折叠?



