天天看點

【map】PAT A1054 The Dominant Color (20分)題目描述知識點我的實作

文章目錄

  • 題目描述
  • 知識點
  • 我的實作
    • 碼前思考
    • 代碼實作
    • 碼後反思

題目描述

【map】PAT A1054 The Dominant Color (20分)題目描述知識點我的實作

知識點

STL

我的實作

碼前思考

題目中說了一定存在,那麼每次判斷就好了,水題!

代碼實作

#include <iostream>
#include <map>
using namespace std;
int main() {
    int m, n;
    scanf("%d %d", &m, &n);
    map<int, int> arr;
    int half = m * n / 2;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            int temp;
            scanf("%d", &temp);
            arr[temp]++;
            if(arr[temp] > half) {
                printf("%d", temp);
                return 0;
            }
        }
    }
    return 0;
}
           

碼後反思

感覺自己去年寫的代碼有點挫,多寫了好多不必要的東西:

#include<stdio.h>
#include<map>
using namespace std;

int main(){
	map<int,int> mp;
	
	int m,n;
	scanf("%d %d",&m,&n);
	
	int maxKey;
	int maxNum;
	
	for(int i=0;i<n;i++){
		for(int j=0;j<m;j++){
			int now;
			scanf("%d",&now);
			if(mp.find(now) != mp.end()){
				mp[now] += 1;
			}else{
				mp[now] = 1;
			}
			if(mp[now] > m*n/2){
				maxKey = now;
				break;
			}
		}
	}
	
	printf("%d",maxKey);
	return 0;
}