【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>
using namespace std;
using ll = long long;
int main() { ios::sync_with_stdio(false); cin.tie(0); int n, ai; cin >> n; map<ll, ll> m; while (n--) { cin >> ai; ++m[ai]; } 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; }
|