您的位置:首页 > 其它

PAT甲题题解-1054. The Dominant Color (20)-排序/map

2017-03-12 15:49 375 查看
原本用map,发现超时了,后来便先用数组存储排个序,最后for一遍统计每种颜色出现的次数(每种颜色的首位索引相减+1),找出最多的即可。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <map>
using namespace std;
const int maxn=500000;
long long color[maxn];

int main()
{
int m,n;
scanf("%d %d",&m,&n);
long long a,ans;
int cnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%lld",&a);
color[cnt++]=a;
}
}
sort(color,color+cnt);
int tmp;
int last=0;//每种颜色的第一个索引
int maxcnt=0;
ans=color[0];
color[cnt]=-1;
for(int i=1;i<=cnt;i++){
if(color[i]!=color[i-1]){
tmp=i-last;
if(tmp>maxcnt){
maxcnt=tmp;
ans=color[i-1];
}
last=i;
}
}
printf("%lld\n",ans);
return 0;
}


View Code

然而没注意到题目中,说到出现最多的颜色肯定是大于一半区域的,其实用map映射来统计,只要有出现大于一半的直接输出然后break,是不会超时。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: