CSU2179: 找众数

时间:2023-03-09 13:20:23
CSU2179: 找众数

Description

由文件给出N个1到30000间无序数正整数,其中1≤N≤10000,同一个正整数可能会出现多次,出现次数最多的整数称为众数。求出它的众数及它出现的次数。

Input

输入文件第一行是正整数的个数N,第二行开始为N个正整数。

Output

输出文件有若干行,每行两个数,第1个是众数,第2个是众数出现的次数。

Sample Input

12
2 4 2 3 2 5 3 7 2 3 4 3

Sample Output

2 4
3 4 题意:很好理解,就是找到出现次数最多的个数和对应的值。桶排一下就行。我这利用map的思想,先把所有出现的值和对应的个数存储起来,然后遍历找到最大的次数,再遍历一下找到其值就可以了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
const int maxn=1005;
int n,T;
map<int,int>m;
int main()
{
while(scanf("%d",&n)!=EOF)
{
int x;
while(n--)
{
scanf("%d",&x);
if(m.count(x)==0)
m[x]=1;
else
m[x]++;
}
int ans=0;
map<int,int>::iterator iter;
iter=m.begin();
while(iter!=m.end())
{
ans=max(ans,iter->second);
iter++;
}
iter=m.begin();
while(iter!=m.end())
{
if(ans==iter->second)
printf("%d %d\n",iter->first,iter->second);
iter++;
}
}
return 0;
} /**********************************************************************
Problem: 2179
User: therang
Language: C++
Result: AC
Time:8 ms
Memory:2424 kb
**********************************************************************/