(map)出现最多的数

题目:

给n个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。
样例输入:
10
9 10 27 4 9 10 3 1 2 6
样例输出:
10 2

分析与解答:

遍历map是根据自动键的大小从小到大遍历的。这里如果出现次数相等,也要更新。

#include<iostream>
#include<cstdio>
#include<map>
#include<algorithm>

using namespace std;
map<int,int> mp;
int main(){
	int n,x,a,b;
	cin>>n;
	for(int i=0;i<n;++i){
		cin>>x;
		mp[x]++;
	}
	b=0;
	for(map<int,int>::iterator it = mp.begin();it!=mp.end();it++){
		if(it->second >= b) {
			b=it->second;
			a=it->first;
		}
	}
	cout<<a<<' '<<b;
	return 0;
}
发布了218 篇原创文章 · 获赞 131 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_40828914/article/details/89047293