题目链接:点击打开链接
知识点笔记:
本题如果不用map,思路:由于题目要求必须超过半数,因此有超过半数的数相同,如果采用两两不同的数相互抵消的做法,最后一定会剩下那个超过半数的数字。于是可以设置一个ans存放答案,设置另一个变量count计数ans出现的次数,然后在读入时判断ans与读入的数字是否相等,如果不相等,则令其抵消一次ans,如果相等,则令count加1.当然,如果某步count被抵消至0,则令新的数字为ans。这样剩下来的数字一定是所求数字
AC代码:
#include <iostream>
#include <map>
using namespace std;
map<int,int> count;
int main() {
int n,m,color;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&color);
if(count.find(color)!=count.end()) count[color]++;
else count[color]=1;
}
}
int k,max=0;
for(map<int,int>::iterator it=count.begin();it!=count.end();it++)
{
if(it->second>max)
{
max=it->second;
k=it->first;
}
}
printf("%d\n",k);
return 0;
}