pat a1054 the dominant color

题目A1054 The Dominant Color

1054_1

1054_2

题意

  在$M*N$的矩阵中找出出现次数最多的数,就是找众数。

思路

  直接用$hash$来存每个数出现的次数,但由于值较大,不能用数组来存,所以想到用$map$来存。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#include<iostream>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
map<int,int>mp;
int n,m,x;
int ()
{
scanf("%d%d",&n,&m);
for(int i=0;i<n*m;i++)
{
scanf("%d",&x);
if(mp.find(x)!=mp.end()) mp[x]++;
else mp[x]=1;
}
int ans=0,maxn=-1;
for(auto it=mp.begin();it!=mp.end();it++)
{
if(it->second>maxn)
maxn=it->second,ans=it->first;
}
printf("%dn",ans);
return 0;
}