点击这里查看题目
其实跟WOJ-203非常像,但是当主元素出现次数刚好为N/2的时候,结果不一定正确,所以这道题我用了map做(其实就是哈希),消耗空间省时间。并不能像WOJ-203的做法一样只用了O(1)的空间
#include<iostream>
#include<map>
using namespace std;
map <int,int> mp;
int main()
{
int n;
while(cin>>n)
{
int tmp,maxx=0,ans;
mp.clear();
while(n--)
{
scanf("%d",&tmp);
mp[tmp]++;
if(mp[tmp]>maxx)maxx=mp[tmp],ans=tmp;
}
cout<<ans<<endl;
}
}