众数问题
Description
给定含有n个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数。多重集S中重数最大的元素称为众数。
例如,S={1,2,2,2,3,5}。多重集S的众数是2,其重数为3。
Input
第1行多重集S中元素个数n(n<=50000);接下来的n 行中,每行有一个自然数。
OutPut
输出文件有2 行,第1 行给出众数,第2 行是重数。(如果有多个众数,只输出最小的)
Example
input
6
1
2
2
2
3
5
output
2
3
Problem solving
主要是利用C++中的map函数,一个用来保存数字,一个用来保存数字的个数。
m[a]++是每次增加新数字就让对应的map加1,最后利用迭代器遍历map容器,it->first代表map容器中的第一个数据,it->second代表map中的第二个数据。
最后遍历找到出现的最多的数字与次数。
Code
//https://www.dotcpp.com/oj/problem1184.html
#include<bits/stdc++.h>
using namespace std;
int main() {
map<int,int> m;
int t;
scanf("%d",&t);
for(int j=0; j<t; j++) {
int a;
scanf("%d",&a);
m[a]++;
}
int ans = -1;
int id;
map<int,int>::iterator it;
for(it = m.begin(); it!=m.end(); it++) {
if(it->second>ans) {
ans = it->second;
id = it->first;
}
}
printf("%d\n%d",id,ans);
return 0;
}
Comments | NOTHING