1054 The Dominant Color

1054 The Dominant Color

題目大意

給出N行M列的數字矩陣,找出超過半數的出現次數最多的數字。

注意

1、很典型的映射思路
2、map真的很好用,如果用二維數組映射,就需要先構造一個特別大的數組。而map可以很方便的建立映射關係,通過find函數實現查詢。
mp.find(key)返回迭代器
mp.erase(key)刪除某對映射
mp.erase(it) map.erase(it_first,it_last)
it->first,it->second通過迭代器訪問鍵和值

代碼

#include<stdio.h>
#include<map>
#include<iostream>
using namespace std;
map<int,int> hashTable;

int main(void){
    int m,n;
    scanf("%d %d",&m,&n);
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++){
            int tmp;
            scanf("%d",&tmp);
            //如果之前已經輸入這個數
            if(hashTable.find(tmp)!=hashTable.end())hashTable[tmp]++;
            else hashTable[tmp]=1;//如果第一次輸入這個數
        }
    int k=0,max=0;
    for(map<int,int>::iterator it = hashTable.begin();it!=hashTable.end();it++){
        if(it->second>k){k=it->second;max=it->first;}
    }
    printf("%d\n",max);

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章