一個(gè)小小的說明:
每天我會(huì)刷幾道PAT的題目作為學(xué)習(xí)熱身,每當(dāng)有一個(gè)新的知識(shí)點(diǎn)我都很激動(dòng)的把它們記錄下來,生怕忘掉。為了自己看著也方便,我就寫在簡書里面。但是不可能每天根據(jù)做了做多少題就更新幾篇文章。想想就累人。所以,每天更新最多兩篇,這是我的想法。
如果真的有一些好的知識(shí),不更不行的那種,我計(jì)劃再單獨(dú)開一個(gè)文章,連續(xù)記錄不斷更新。
原題鏈接
The Dominant Color
思路:
這個(gè)題目的意思很直截了當(dāng),根據(jù)給出的一堆數(shù)字,找出出現(xiàn)最多的。大致一想,解法就不少。書本上給出map的用法,也當(dāng)做一個(gè)map的練習(xí)題吧。
關(guān)鍵:
開一個(gè)map映射
鍵:題目給的數(shù)字,值:出現(xiàn)的次數(shù)
代碼如下:
#include <cstdio>
#include <map>
using namespace std;
int main()
{
int m, n, temp;//m:列數(shù) n:行數(shù)
scanf("%d %d", &m, &n);
map<int, int> count;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf("%d", &temp);
if (count.find(temp) != count.end())
{
count[temp]++;
}
else
{
count[temp] = 1;
}
}
}
//輸入完畢
int k = 0;
int 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", k);
return 0;
}
總結(jié)
這道題的思路相當(dāng)簡單了。但我們還是要吸取一點(diǎn)經(jīng)驗(yàn):
map的作用不僅局限于string與int之間的對應(yīng)關(guān)系,還可以做到記錄次數(shù)的作用。
map<int,int> count//我覺得很棒棒