试题编号:

201312-1

试题名称:

出现次数最多的数

时间限制:

1.0s

内存限制:

256.0MB

问题描述:

问题描述

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

输入格式

  输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
  输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。

输出格式

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

样例输入

6
10 1 10 20 30 20

样例输出

10

解题思路:

这题直接用map来进行操作,其中map的key是正整数,value是其在数组中出现的次数。ans用来存放出现次数最多的正整数,max用来记录出现最多的次数,for-each循环遍历map,若某个数出现次数大于max,更新出现最多的次数max和出现最多次的正整数ans。最后输出ans即可。

100分代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<int,int> m;  //map的key是正整数,value是其在数组中出现的次数
    int n;
    cin >> n;   //n个正整数
    for (int i = 0; i < n; i++)   //输入正整数并记录它们在数组中出现的次数
    {
        int temp;
        cin >> temp;
        m[temp]++;
    }
    int ans,max=0;   //ans用来存放出现次数最多的正整数,max用来记录出现最多的次数
    for(auto it:m)   //for-each循环遍历map
    {
        if(it.second > max)    //若某个数出现次数大于max
        {
            max = it.second;   //更新出现最多的次数max
            ans = it.first;    //更新出现最多次的正整数
        }
    }
    cout << ans << endl;
    return 0;
}

——————————————2019.09.07更新——————————————————

#include <bits/stdc++.h>
using namespace std;
#define Up(i,a,b) for(int i = a; i <= b;i++)

int main()
{
    int n;
    cin >> n;
    map<int,int> m;
    int ans,cnt = 0;
    Up(i,1,n)
    {
        int _;
        cin >> _;
        m[_]++;
        if(m[_] > cnt)
        {
            cnt = m[_];
            ans = _;
        }
        else if(m[_] == cnt)
        {
            ans = min(ans,_);
        }
    }
    cout << ans << endl;
    return 0;
}