PAT-ADVANCED1054——The Dominant Color

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/83902839

我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED

原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805422639136768

题目描述:

题目翻译:

1054 主色彩

在计算机内存的幕后,颜色总是被称为每个像素的一系列24位信息。 在图像中,具有最大比例区域的颜色称为主色。 严格主色是指其主色占总面积的一半以上。 现在给出分辨率M乘N的图像(例如,800×600),你应该指出严格主色。

输入格式:

每个输入文件包含一个测试用例。 对每个测试用例,第一行包含2个正数:M(<= 800)和N(<= 600),它们是图像的分辨率。 然后是N行,每行包含[0, 2]范围内的M个数字颜色(数字颜色在[0, 2 ^ 24)范围内)。题目保证每个输入图像都存在严格主色。 一行中的所有数字都用空格分隔。

输出格式:

对每个测试用例,在一行中简单输出其主色。

输入样例:

5 3
0 0 255 16777215 24
24 24 0 0 24
24 0 24 24 24

输出样例:

24

知识点:计数

思路:用map集合来计算每种颜色的数量

时间复杂度是O(M * N)。空间复杂度是O(n),其中n为输入不同颜色数。

C++代码:

#include<iostream>
#include<map>

using namespace std;

int main(){
	int M, N;
	scanf("%d %d", &M, &N);
	int num;
	map<int, int> numMap;
	for(int i = 0; i < N; i++){
		for(int j = 0; j < M; j++){
			scanf("%d", &num);
			numMap[num]++;
		}
	}
	int max = 0;
	int dominant = -1;
	for(map<int, int>::iterator it = numMap.begin(); it != numMap.end(); it++){
		if(it->second > max){
			dominant = it->first;
			max = it->second;
		}
	}
	printf("%d\n", dominant);
	return 0;
} 

C++解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/83902839