Week12 A - 必做题 - 1
给出n个数,zjm想找出出现至少(n+1)/2次的数, 现在需要你帮忙找出这个数是多少?
Input
本题包含多组数据:
每组数据包含两行。
第一行一个数字N(1<=N<=999999) ,保证N为奇数。
第二行为N个用空格隔开的整数。
数据以EOF结束。
Output
对于每一组数据,你需要输出你找到的唯一的数。
Sample Input
5
1 3 2 3 3
11
1 1 1 1 1 5 5 5 5 5 5
7
1 1 1 1 1 1 1
Sample Output
3
5
1
解题思路
用数组记录每个数出现的次数
每次读入时都检查当前的数出现次数
Code
#include<iostream>
#include<string.h>
using namespace std;
int n;
int ans;
int t[1000000];
int main(){
int s;
while(cin>>n){
ans=0;
memset(t,0,sizeof(t));
for(int i=0;i<n;i++){
cin>>s;
t[s]++;
if(t[s]>=(n+1)/2){
ans=s;
}
}
cout<<ans<<endl;
}
}