计蒜客习题6:蒜头君面试(map)STL

 蒜头君来蒜厂面试的时候,曾经遇到这样一个面试题: 
给定 n 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给蒜头君难住了。现在蒜头君来考考你。 
输入格式 
第一行输入一个整数n(1≤n≤100000),接下来一行输入n个 int 范围内的整数。 
输出格式 
输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。 
样例输入 
10 
9 10 27 4 9 10 3 1 2 6 
样例输出 
10 2

#include <bits/stdc++.h>
using namespace std;

map<int,int> mp;
int main()
{
	int n,ans1,ans2=0,x;
	cin>>n;
	for(int i=0;i<n;++i)
	{
		cin>>x;
		mp[x]++;		
	}
	for(map<int,int>::iterator it = mp.begin();it!=mp.end();++it)
	{
		if((it->second)>=ans2){
			ans1=it->first;
			ans2=it->second;
			//map默认是从小到大排序 ,输出first的一定是最大值 
		}	
	}
	cout<<ans1<<" "<<ans2<<endl;
 	return 0;
} 

猜你喜欢

转载自blog.csdn.net/intmain_S/article/details/89673362