目录
题目
- 1000ms
- 131072K
蒜头君来蒜厂面试的时候,曾经遇到这样一个面试题:
给定 n 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给蒜头君难住了,现在蒜头君来考考你。
输入格式
第一行输入一个整数 n (1≤n≤100000),接下来一行输入 n 个int范围内的整数。
输出格式
输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。
输出时每行末尾的多余空格,不影响答案正确性
要求使用「文件输入输出」的方式解题,输入文件为 interview.in,输出文件为 interview.out
样例输入1
5
1 1 2 3 4
样例输出1
1 2
样例输入2
10
9 10 27 4 9 10 3 1 2 6
样例输出2
10 2
题解:
知识点:map的应用
分析:本题难点就在于测试数据中有负数,就不能用数组,而map相当于是数组的迭代版,所以就用map来存数据(计数),注意迭代器的使用。
代码:
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
int main(){
freopen("interview.in","r",stdin);
freopen("interview.out","w",stdout);
map<int,int>mp;//第一个存数字,第二个存次数
int n;
cin>>n;
for (int i=0,x;i<n;i++){
cin>>x;
mp[x]++;//用map来计数
}
int ans=-1,cnt=0;//ans记录出现次数,cnt记录数字
for (map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
if (it->second>=ans){//注意指针、迭代器的使用
ans=it->second;//
cnt=it->first;
}
}
cout<<cnt<<" "<<ans;
return 0;
}