题目

蒜头君来蒜厂面试的时候,曾经遇到这样一个面试题:

给定 <math> <semantics> <mrow> <mi> n </mi> </mrow> <annotation encoding="application&#47;x&#45;tex"> n </annotation> </semantics> </math>n 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给蒜头君难住了。现在蒜头君来考考你。

输入格式

第一行输入一个整数 <math> <semantics> <mrow> <mi> n </mi> <mo> ( </mo> <mn> 1 </mn> <mo> ≤ </mo> <mi> n </mi> <mo> ≤ </mo> <mn> 100000 </mn> <mo> ) </mo> </mrow> <annotation encoding="application&#47;x&#45;tex"> n(1 \le n \le 100000) </annotation> </semantics> </math>n(1n100000),接下来一行输入 <math> <semantics> <mrow> <mi> n </mi> </mrow> <annotation encoding="application&#47;x&#45;tex"> n </annotation> </semantics> </math>n 个 int 范围内的整数。

输出格式

输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。

样例输入

5

1 1 2 3 4

样例输出

1 2

样例输入

10

9 10 27 4 9 10 3 1 2 6

样例输出

10 2

题解

基本 map 应用

#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
int main(){
	map<int,int> m;
	int n,t;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>t;
		if(m.count(t))
			m[t]++;
		else
			m[t] = 1;
	}
	int key = t;
	for(map<int,int>::iterator it = m.begin();it!=m.end();it++){
		if(m[key] < (it->second))
			key = (it->first); 
		else if(m[key] == (it->second))
			key = max((it->first),key);
	} 
	cout<<key<<" "<<m[key];
	return 0;
} 

返回目录,查看更多