题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1029
这本来是一道水题,但是还是错了很多次,因为有可能没有解,不用输出。也可以利用排序。
写这篇博客,主要是一种思想,
参考代码:http://blog.sina.com.cn/s/blog_ace0c3ed01016v66.html
利用两个数进行pk,比如说:1 2 3 4 3 3 3
1和2抵消,3和4抵消,如此循环,剩下肯定是出现次数最多的。
代码:
#include <iostream>
using namespace std;
int main()
{
int T,tempa,tempb,times;
while(scanf("%d",&T)!=EOF)
{
times=0;
for(int i=0;i<T;i++)
{
scanf("%d",&tempa);
if(times==0){
tempb=tempa;
times=1;
}
else if(tempa!=tempb)
times--;
else times++;
}
printf("%d\n",tempb);
}
return 0;
}
当初我写的代码:
#include <iostream>
using namespace std;
int cet[1000001];
int main()
{
int n,k;
while(cin>>n)
{
int max((n+1)/2);
memset(cet,0,sizeof(cet));
for(int i=1;i<=n;i++)
{ cin>>k;
cet[k]++;
}
k=0;
for(int i=1;i<=1000000;i++)
if(cet[i]>=max){
max=cet[i];
k=i;
}
if(k) cout<<k<<endl;
}
return 0;
}
参考代码:
#include<stdio.h>
#include<string.h>
int flag[1000001];
int main()
{ int n,i,j,count,N;
while(scanf("%d",&n)!=EOF)
{ N=n;
memset(flag,0,sizeof(flag));
while(n--)
{ scanf("%d",&j);
flag[j]++;
}
count=flag[1];
j=0;
for(i=1;i<1000001;i++)
if(flag[i]>=count) {
count=flag[i];
j=i;
}
if(count>=(N+1)/2) printf("%d\n",j);
}
return 0;
}