[PAT-A 1054]The Dominant Color

在这里插入图片描述
题目大意:
给出N行M列的矩阵,求其中出现次数最多的矩阵。

思路:
1)建立map<int,int> count,表示数字与其出现次数的映射关系。
2)对每个输出的数字,使用find查找是否在map中出现过,如果已经存在,则加一,否则,将其出现的次数置为1。
3)最后遍历map,寻找出现最多的数字输出。
*这里用HASH的话可能会超时,用HASH的地方都可以考虑一下map。

AC代码:

//PAT_A 1054
#include<cstdio>
#include<map>
using namespace std;
int main() {
	int n, m, col;
	(void)scanf("%d%d", &n, &m);
	map<int, int>count;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			(void)scanf("%d", &col);
			if (count.find(col) != count.end())count[col]++;
			else count[col] = 1;
		}
	}
	int k = 0, MAX = 0;
	for (map<int, int>::iterator it = count.begin(); it != count.end(); it++) {
		if (it->second > MAX) {
			k = it->first;
			MAX = it->second;
		}
	}
	printf("%d\n", k);
	return 0;
}
发布了142 篇原创文章 · 获赞 1 · 访问量 4566

猜你喜欢

转载自blog.csdn.net/weixin_44699689/article/details/104307615