问题描述
给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
样例输出
10
思路:
1、使用哈希表存储每个数字出现的次数。
2、遍历哈希表,用max存储哪一个数字出现的次数最多,并用res记录数字,当出现的次数一样时通过比较数字本身大小来判断,只存储数字小的那一个。
3、输出res。
代码实现:
#include<iostream>
#include<unordered_map>
using namespace std;
int main() {
int n, m;
cin >> n;
unordered_map<int, int>map;
while (n--)
{
int i;
cin >> i;
map[i]++; //累加每个数字出现的次数
}
int max = 0, res = 10001;
for (auto m : map) //map.first是数字本身也就是哈希表的key,map.second是数字出现的次数,也就是哈希表的value
{
if (m.second > max)
{
max = m.second;
res = m.first;
}
else if (m.second == max)
res = m.first > res ? res : m.first;
}
cout << res;
return 0;
}