给定 n 个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入的第一行只有一个正整数 n,表示数字的个数。输入的第二行有 n 个整数$a_1,a_2,\cdots,a_n$。相邻的数用空格分隔。
输出这 n 个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
可以使用 map 来存储数字及其对应的出现次数,然后使用 max_element 函数统计出现次数最多的数字即可。
#include <bits/stdc++.h>
using namespace std;
using gg = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
gg ni, ai;
cin >> ni;
map<gg, gg> m;
while (ni--) {
cin >> ai;
++m[ai];
}
cout << max_element(m.begin(), m.end(),
[](const pair<gg, gg>& p1, const pair<gg, gg>& p2) {
return p1.second < p2.second;
}) ->first;
return 0;
}