0
点赞
收藏
分享

微信扫一扫

【2018】求众数(map)

RockYoungTalk 2022-03-11 阅读 44

题目:

题很简单,但要注意用10^5做数组下标,开不了那么大,故用map
map要点:

  • 如果是字符串到整型的映射,必须使用string而不是char数组
  • 访问方式:(1)直接用下标访问:mp['s'];(2)迭代器访问:键it->first,值it->second
  • map会以键从小到大的顺序自动排序
#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
int main() {
	map<int, int> mp;
	int n,x,maxd=-1,index=-1;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> x;
		mp[x]++;
	}
	map<int, int>::iterator it;
	for (it = mp.begin(); it != mp.end(); it++) {
		if (it->second > maxd) {
			maxd = it->second;
			index = it->first;
		}
		
	}
	cout << index;
	system("pause");
	return 0;
}
举报

相关推荐

0 条评论