LJY • 1年前
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
unordered_map<int, int> countMap;
// 读取数组并统计每个元素出现的次数
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
countMap[num]++;
}
// 找出出现次数最多的数,如果有多个众数,选择最小的
int mostFrequent = -1;
int maxCount = 0;
for (auto& pair : countMap) {
if (pair.second > maxCount || (pair.second == maxCount && pair.first < mostFrequent)) {
mostFrequent = pair.first;
maxCount = pair.second;
}
}
// 输出结果
cout << mostFrequent << endl;
return 0;
}
评论:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
unordered_map<int, int> countMap;
// 读取数组并统计每个元素出现的次数
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
countMap[num]++;
}
// 找出出现次数最多的数,如果有多个众数,选择最小的
int mostFrequent = -1;
int maxCount = 0;
for (auto& pair : countMap) {
if (pair.second > maxCount || (pair.second == maxCount && pair.first < mostFrequent)) {
mostFrequent = pair.first;
maxCount = pair.second;
}
}
// 输出结果
cout << mostFrequent << endl;
return 0;
} z坐坐坐坐下