小明最近在上数学课,老师给小明布置了个作业:在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;
}