C++ 算法:求多重集合的重数和众数
C++ 算法:求多重集合的重数和众数
给定含有 N 个元素的多重集合 S,每个元素在 S 中出现的次数称为该元素的重数,多重集合 S 中重数最大的元素称为多重集合 S 的众数,众数的重数称为多重集合 S 的重数。
问题描述
对于一个给定的多重集合 S,求出它的重数和众数。
解决方案
我们可以使用哈希表来存储每个元素的重数,然后遍历哈希表,找到其中重数最大的元素,即为众数。同时,将哈希表中所有元素的重数累加起来,即为多重集合 S 的重数。
以下为 C++ 代码实现:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
int n, maxCount = 0, sumCount = 0, mode = 0;
unordered_map<int, int> counts;
cin >> n;
// 统计每个元素的重数
for (int i = 0; i < n; i++) {
int num;
cin >> num;
counts[num]++;
}
// 遍历哈希表,找到众数和重数
for (auto it = counts.begin(); it != counts.end(); it++) {
if (it->second > maxCount) {
maxCount = it->second;
mode = it->first;
}
sumCount += it->second;
}
cout << "重数:" << sumCount << endl;
cout << "众数:" << mode << ",重数为:" << maxCount << endl;
return 0;
}
总结
使用哈希表可以快速地解决多重集合 S 的重数和众数问题。通过本题,我们可以更好地理解哈希表的应用。
原文地址: https://www.cveoy.top/t/topic/lmXH 著作权归作者所有。请勿转载和采集!