CCF201312-1

来源:互联网 发布:知乎ipad客户端 编辑:程序博客网 时间:2024/06/06 00:49

出现次数最多的数

问题描述
  给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
  输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
  输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
  输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
样例输出
10

问题分析:
方法一:
使用count[a[i]]数组进行统计,使用for循环比较哪个数出现的次数最多。
PS:注意变量的取值范围,最好比要求的范围大,否则难拿满分。

#include <iostream>#define N 1001#define M 10001using namespace std;//出现次数最多的数33int main(){    int n,num;    int max=0,count[M]={0};    cin>>n;    int a[N];    for(int i=0;i<n;i++){        cin>>a[i];        count[a[i]]++;    }    //找出出现次数最多的数    for(int i=0;i<M;i++){        if(count[i]>count[max]){            max=i;        }        /* 此段代码没有必要,请读者思考         else if(count[i]==count[max]&&i<max){            max=i;        }        */         }    }     num=max;    cout<<num<<endl;    return 0;}

方法二:
使用STL容器map进行统计。

#include <iostream>#include <map>//出现次数最多的数using namespace std;int main(){    //map<int,string>m是声明一个map容器    map<int, int> m;    int n,num;    //输入数据,构建Map    cin >> n;    for(int i=0; i<n; i++) {        cin >> num;        m[num]++;    }    //找出出现次数最多的数    //map<int,string>::iterator it是声明一个迭代器    int ans, count=0;    for(map<int,int>::iterator it=m.begin(); it!=m.end(); it++){         if(it->second > count) {                                             count = it->second;            ans = it->first;        }    }    cout<<ans<<endl;     return 0;}
原创粉丝点击