出现次数最少的数

闲来无事,想着把ccf刷到三百分




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

我的代码

#include <iostream>
using namespace std;

int main()
{
    int n=0;
    cin>>n;
    int mat[n];
    int store_name[n];
    int store_num[n];
    int j=0;
    int curlocation=0;
    int maxname=0;
    int maxnum=0;
    for(int i=0;i<n;i++)
    {
        cin>>mat[i];
        if(i==0)//避免0和0的比较?
        {
            store_name[0]=mat[0];
            store_num[0]=1;
            j++;
            curlocation=j-1;
        }
        else
        {
            int matchflag=0;
            for(int k=0;k<j;k++)
            {
                if(mat[i]==store_name[k])
                {
                    store_num[k]++;
                    matchflag=1;
                    curlocation=k;
                }               
            }
            if(matchflag==0)
            {
                store_name[j]=mat[i];
                store_num[j]=1;
                j++;
                curlocation=j-1;
            }
        }
        if(store_num[curlocation]>maxnum||(store_num[curlocation]==maxnum&&store_name[curlocation]<maxname))
        {
            maxnum=store_num[curlocation];
            maxname=store_name[curlocation];
        }   
    }
    cout<<maxname; 
    return 0;
} 

网上的参考代码

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main(){
     int n;
     cin>>n;
     int m[10001]={0};
     for(int i=0;i<n;i++){
          int x;
          cin>>x;
          m[x]++;
     }
     int max=0;
     for(int i=1;i<10001;i++){
          if(m[i]>m[max]){
           max=i;
          }
     }
     cout<<max<<endl;
     return 0;
}

参考代码使用了数组下标来记录数据的值,用数组的值来记录数据出现的次数
仔细看了一下题目,所给出的范围并没有0,如果有零的话可以用数组的第一个元素存储0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值