CSP201312-1出现次数最多的数

题目传送门


题目分析
  map<int,int>是一个键值对,键为int类型,值也是int类型,map会根据键自动进行排序。
  将输入的每一个数都存放到map<int, int> numbers中,若这个数在map中已经存在,则将值加1,若不存在,则创建新的键值对,并令值为1。numbers[num]++就可以实现上述功能,若num不在numbers中,则首先创建键值对,键为num,值默认为0,之后值自加,变为1。
  全部输入完成之后,遍历numbers,寻找值最大的键。


源代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
	int n,num;
	int times = 0;//出现的次数
	map<int, int> numbers;
	cin >> n;
	while (n--) {
		cin >> num;
		numbers[num]++;
	}
	for (auto i : numbers) {
		if (i.second > times) {
			times = i.second;
			num = i.first;
		}
	}
	cout << num;
}

题目

问题描述
  给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
  输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
  输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
  输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
样例输出
10

发布了172 篇原创文章 · 获赞 81 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_43074474/article/details/104741079