Description
小信来应聘程序员的时候,曾经遇到这样一个面试题:
给定 n 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给小信难住了。现在小信来考考你。
Input
第一行输入一个整数 n(1 <= n <= 100000),接下来一行输入 n 个 int 范围内的整数。
Output
输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。
Sample Input 1
5
1 1 2 3 4
Sample Output 1
1 2
Sample Input 2
10
9 10 27 4 9 10 3 1 2 6
Sample Output 2
10 2
看到这道题,我想到了众数,只是本题要输出次数,和出现重复判断值最大的那个罢了。
代码很简单:
#include <bits/stdc++.h>
using namespace std;
int main(){
map<int,int>mp;
int n;
cin>>n;
for(int i=0;i<n;i++){
int num;
cin>>num;
mp[num]++;
}
map<int,int>::iterator it;
int mx=0,num;
for(it=mp.begin();it!=mp.end();it++){
if((*it).second>=mx){
mx=(*it).second;
num=(*it).first;
}
}
cout<<num<<" "<<mx;
return 0;
}