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
题解
此题比较简单,没有什么复杂的思想。
有一个数组cnt[1000000],用cnt[i]来记录i一共出现了几次。因为题目中n<=999999,且有一半以上的数值是相同的,所以猜测应该不会有大于1000000的数值出现(事实证明猜测合理)。
每输入一个数值i,对应的cnt[i]就加1,并检查cnt[i]是否>=(n+1)/2。是则输出i,本次输入循环结束,break,进行下一组数据。需要注意的是循环结束前要把剩下的缓冲区中的数字取出来,以免影响下一组数据。进行每组数据前要将cnt全部赋值为0。
代码
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int cnt[1000000];
int main(int argc, char** argv) {
int n;
while(scanf("%d",&n)!=EOF){
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=n;i++){
//cout<<"time "<<i<<endl;
int a;scanf("%d",&a);
cnt[a]++;
if(cnt[a]>=(n+1)/2){
printf("%d\n",a);
for(int j=i+1;j<=n;j++){
int b;scanf("%d",&b);
}
break;
}
}
}
return 0;
}