题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805422639136768
之前以为是大数,用的string映射int,结果用cin,cout超时。后来改成int映射int就不超时了。然后遇到一个问题,原来题目中说的dominant color大于一半,并不是。最后一个测试用例就小于一半,坑啊。我之前代码是这样的:
#include <cstdio>
#include <map>
using namespace std;
map<int, int> a;
int main(){
int n, m;
scanf("%d%d", &m, &n);
int str;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
scanf("%d", &str);
if(a.find(str) != a.end()){
a[str]++;
if(a[str] * 2 > m * n){
printf("%d\n", str);
return 0;
}
}
else
a[str] = 1;
}
}
}
最后一个用例打死都过不到,也考虑过是不是没有取等,因为可能只有两个颜色,结果最后一个用例还是错误,于是参考了算法笔记。它就没有利用大于一半这个条件,只是找最大值。然后结果就对了。
#include <cstdio>
#include <map>
using namespace std;
map<int, int> a;
int main(){
int n, m;
scanf("%d%d", &m, &n);
int str;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
scanf("%d", &str);
if(a.find(str) != a.end()){
a[str]++;
if(a[str] * 2 > m * n){
printf("%d\n", str);
return 0;
}
}
else
a[str] = 1;
}
}
int max = -1, k;
for(map<int, int>::iterator it = a.begin(); it != a.end(); it++){
if(it->second > max){
k = it->first;
max = it->second;
}
}
printf("%d\n", k);
return 0;
}