题目地址:
https://www.acwing.com/problem/content/3195/
给定 n n n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式:
输入的第一行只有一个正整数 n n n,表示数字的个数。输入的第二行有 n n n个整数 s 1 , s 2 , … , s n s_1,s_2,…,s_n s1,s2,…,sn。相邻的数用空格分隔。
输出格式:
输出这 n n n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
数据范围:
1 ≤ n ≤ 1000 1≤n≤1000 1≤n≤1000
1 ≤ s i ≤ 10000 1≤s_i≤10000 1≤si≤10000
代码如下:
#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 1010;
int n;
unordered_map<int, int> mp;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
mp[x]++;
}
int res = 0x3f3f3f3f, count = 0;
for (auto t : mp)
if (t.second > count) {
count = t.second;
res = t.first;
} else if (t.second == count)
res = min(res, t.first);
cout << res << endl;
return 0;
}
时空复杂度 O ( n ) O(n) O(n)。