c++众数

小明最近在上数学课,老师给小明布置了个作业:在n 个数里找出所有的众数。众数的定义是这样的:在所有数当中出现次数最多的数被称为众数。并且根据定义,众数有可能有多个。你能解决这个问题吗?

输入格式

第一行一个整数n。

第二行有n 个整数,ai 表示第i 个数。

输出格式

输出一行,包括一个整数k,表示众数的个数。

接下来一行包括k 个整数,每个整数都表示一个众数,并且从小到大输出。

输入/输出例子1

输入:

10

3 3 3 2 3 1 2 2 1 2

输出:

2

2 3

#include<bits/stdc++.h>
using namespace std;
map<int,int>person;
int M[1000000];
int t;
int main(){
    int n,id=0,Max=-100;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int s;
        cin>>s;
        person[s]++;
    }
    map<int,int>::iterator it;
    for(it=person.begin();it!=person.end();it++)
    {
        if(it->second>Max)
        {
            Max=it->second;
        }
    }
    for(it=person.begin();it!=person.end();it++)
    {
        if(it->second==Max)
        {
            id++;
        }
    }
    cout<<id<<endl;
    for(it=person.begin();it!=person.end();it++)
    {
        if(it->second==Max)
        {
            cout<<it->first<<" ";
        }
    }
    return 0;
}

给定 n 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。

输入格式

第一行输入一个整数 n(1≤n≤1000000),接下来一行输入 n 个 int 范围内的整数。

输出格式

输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。

输入/输出例子1

输入:

5

1 1 2 3 4

输出:

1 2

输入/输出例子2

输入:

10

9 10 27 4 9 10 3 1 2 6

输出:

10 2

#include<bits/stdc++.h>
using namespace std;
map<int,int>person;
int main(){
    int n,id=0,Max=-100;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int s;
        cin>>s;
        person[s]++;
        if(person[s]>Max)
        {
            Max=person[s];
            id=s;
        }
    }
    cout<<id<<" "<<Max;
    return 0;
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪子小院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值