出现次数最多的数字 (100/100 分数)
题目描述
给定一串已经从小到大排好顺序的数字,其中有些数字出现了多次,请输出出现次数最多的那个数字。
如果有两个数字出现的次数一样,那么其中较小的那个。
输入描述
输入一个整数n,表示有n个已经排好顺序的数字,其中(0 < n < 1000).
接下来n行,每行一个数字。
输出描述
输出为一行,表示出现次数最多的那个数字。
样例输入
4
1
2
2
3
5
1
2
2
3
3
样例输出
2
2
//此题数组已经排序好
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int* a = new int[n];
for(int i=0; i<n; ++i){
cin >> a[i];
}
int num=a[0];//出现次数最多的那个数
int max_cnt=1;//最大出现次数
int cnt=1;//记录每个数字出现次数
for(int i=1; i<n; ++i){
if(a[i]==a[i-1]){
++cnt;
}
else{
if(cnt>max_cnt){
max_cnt = cnt;
num = a[i-1];
}
cnt = 1;//cnt要归一
}
}
cout << num << endl;
return 0;
}