无序关联容器
unordered_map是C++标准库中的一个关联容器,它存储的元素是键值对,其中每个键在容器中只出现一次。unordered_map的键是无序的,即元素在容器中的顺序是不确定的,但是可以通过键来快速查找对应的值。
unordered_map的实现是基于哈希表(hash table)的,因此其插入、删除和查找操作的时间复杂度通常为O(1)。但是,由于哈希表实现中存在冲突,实际的时间复杂度可能会略高于O(1)。
使用unordered_map需要包含头文件<unordered_map>
csp出现次数最多的数
问题描述
给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
6
10 1 10 20 30 20
样例输出
10
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int findMostCommonNumber(vector<int>& nums) { //传引用
unordered_map<int, int> countMap; //无需关联容器
for (int num : nums) {
countMap[num]++; //它存储的元素是键值对,其中每个键在容器中只出现一次
}
int maxCount = 0;
int mostCommonNum = 0;
for (auto it = countMap.begin(); it != countMap.end(); ++it) {
if (it->second > maxCount) {
maxCount = it->second;
mostCommonNum = it->first;
}
// //这样的数有多个,请输出其中最小的一个。
if(it->second == maxCount){
maxCount = it->second;
mostCommonNum=(it->first<mostCommonNum?it->first:mostCommonNum);
}
}
return mostCommonNum;
}
int main() {
int n;
cin>>n;
vector<int> nums(n);
for(int i=0;i<n;i++){
cin>>nums[i];
}
//vector<int> nums = {1, 2, 3, 2, 4, 3, 3};
int result = findMostCommonNumber(nums);
cout << result << endl;
return 0;
}
/*
6
10 1 10 20 30 20
*/
也可以这样写:
// pdf上的答案
#include <iostream>
#include <map>
using namespace std;
void test01()
{
int n;
cin >> n;
// 用一个map存储每个整数(num)及其出现的次数(count)
// map会根据它的key进行自动排序(升序)
map<int, int> countMap;
while (n--)
{
int num;
cin >> num;
// 增加键(num)对应的值(count),如果键不存在将自动创建,并值初始化为0
countMap[num]++;
}
// map中的元素是以键值对的形式存储的,first代表键,second代表值
int resultNum = countMap.begin()->first; // 最多次数的数
int maxCount = countMap.begin()->second; // 最多次数
// 遍历map找出出现次数最多的数
for (auto &p : countMap)
{
// 如果当前键值对的值大于maxCount或者值等于maxCount且键小于resultNum
if (p.second > maxCount || (p.second == maxCount && p.first < resultNum))
{
resultNum = p.first;
maxCount = p.second;
}
}
// 输出出现次数最多的数
cout << resultNum;
}
int main()
{
test01();
return 0;
}