1. 程式人生 > >PAT-ADVANCED1054——The Dominant Color

PAT-ADVANCED1054——The Dominant Color

我的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++解題報告: