0
点赞
收藏
分享

微信扫一扫

算法训练 出现次数最多的整数


 问题描述
  编写一个程序,读入一组整数,这组整数是按照从小到大的顺序排列的,它们的个数N也是由用户输入的,最多不会超过20。然后程序将对这个数组进行统计,把出现次数最多的那个数组元素值打印出来。如果有两个元素值出现的次数相同,即并列第一,那么只打印比较小的那个值。
  输入格式:第一行是一个整数NN £ 20;接下来有N行,每一行表示一个整数,并且按照从小到大的顺序排列。
  输出格式:输出只有一行,即出现次数最多的那个元素值。
输入输出样例

样例输入

5
100
150
150
200
250

样例输出

150

90分 

 

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <map>
#include <algorithm>
using namespace std ;
typedef long long LL;
const LL mod = 1e9+7 ;
const int MAX = 1e8+10 ;
const int inf = 0x3f3f3f3f ;
map<int ,int > m ;
int main(){
int n ;
cin >> n ;
if(n<0 || n>20 )return 0 ;
int maxx = -inf ;
int minn = inf ;
for(int i = 1 ; i<=n ; i++ ){
int x ;
cin >>x ;
m[x]++ ;
if(maxx <x ){
maxx = x ;
}
if(minn > x ){
minn = x ;
}
}
int v ;
int c = 0 ;
for(int i = minn ; i <=maxx ; i++ ){
if(c <m[i]){
v = i ;
c = m[i] ;
}
}
cout<<v ;


return 0;
}

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <map>
#include <algorithm>
using namespace std ;
typedef long long LL;
const LL mod = 1e9+7 ;
const int MAX = 10005 ;
const int inf = 0x3f3f3f3f ;
map<int ,int > m ;
LL a[MAX];
int main(){
int n ;
cin >> n ;
if(n>0 && n<=20 ){
for(int i = 0 ; i<n ; i++ )
cin >> a[i] ;
int count = 0 , now ;
int max = a[0] ,maxx = 1 ;
for(int i = 0 ; i <n ; i ++ ){
if(now!=a[i]){
now = a[i] ;
count = 1;
}
else{
count++ ;
}
if(maxx <count){
maxx = count ;
max = now ;
}
}
cout<<max<<endl;
}

return 0;
}

 

举报

相关推荐

0 条评论