【CCF CSP-20131201】出现次数最多的数

题意概述

给定 n 个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。

输入输出格式

输入的第一行只有一个正整数 n,表示数字的个数。输入的第二行有 n 个整数$a_1,a_2,\cdots,a_n$。相邻的数用空格分隔。

输出这 n 个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。

数据规模

$$1\le n\le1000,1\le a_i\le10000$$

算法设计

法1:使用桶来计数,计数过程中同步更新

法2:可以使用 map 来存储数字及其对应的出现次数,然后使用 max_element 函数统计出现次数最多的数字即可。

时间

​ 2025年2月28日20:02:00

C++代码

C++法1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<cstdio>

int main(){
int n;
scanf("%d",&n);
int cnt[10001]={};
int num;
int mxCnt=0,maxElem;
while(--n){
scanf("%d",&num);
++cnt[num];
if(cnt[num]>mxCnt){
mxCnt=cnt[num];
maxElem=num;
}else if(cnt[num]==mxCnt&& num<maxElem){
maxElem=num;
}
}
printf("%d",maxElem);
}

C++法2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <bits/stdc++.h> // 包含所有标准库头文件,常用于竞赛编程简化代码

// 使用标准命名空间,避免重复写std::
using namespace std;
// 定义长整型别名ll,方便后续使用
using ll = long long;

int main() {
// 禁用C++与C的输入输出流同步,加快输入输出速度
ios::sync_with_stdio(false);
// 解除cin和cout的绑定,进一步提升输入输出效率
cin.tie(0);

int n, ai; // n: 输入数字的总数, ai: 临时存储每个输入的数字
cin >> n; // 读取数字总数n

// 创建map用于统计数字出现频率,键为数字,值为出现次数
map<ll, ll> m;

// 循环读取每个数字并更新频率统计
while (n--) {
cin >> ai; // 读取当前数字
++m[ai]; // 将该数字的计数加1(若不存在会自动插入)
}

// 在map中查找出现次数最多的元素
cout << max_element(m.begin(), m.end(),
// 自定义比较规则:按出现次数比较
[](const pair<ll, ll>& p1, const pair<ll, ll>& p2) {
return p1.second < p2.second; // 比较两个元素的出现次数
})->first; // 提取出现次数最多元素的键(即原始数字)

return 0;
}