C++ 统计非负整数数组中每个数的出现次数 - 优化算法代码
C++ 统计非负整数数组中每个数的出现次数 - 优化算法代码
本代码使用 C++ 实现统计非负整数数组中每个数的出现次数的功能。算法首先找到数组中的最大数,然后初始化一个计数数组,最后遍历数组并统计每个数出现的次数。
输入描述
第一行 n 是数组的大小。1≤n≤100000。紧接着一行是数组的 n 个元素。
输出描述
按顺序输出每个数的出现次数,一行一个数。如果没有出现过,则输出 0。对于例子中的数组,最大的数是 3,因此我们只统计 {0,1,2,3} 的出现频数。
样例输入 1
5 1 1 2 3 1
样例输出 1
0 3 1 1
代码实现
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int max_num = *max_element(arr.begin(), arr.end()); // 找到数组中的最大数
vector<int> count(max_num+1); // 初始化计数数组
for (int i = 0; i < n; i++) {
count[arr[i]]++; // 计数
}
for (int i = 0; i <= max_num; i++) {
cout << count[i] << endl; // 输出每个数的出现次数
}
return 0;
}
优化点
- 使用
max_element函数快速找到数组中的最大数。 - 使用
vector存储计数数组,方便访问和修改。 - 代码简洁易懂,易于维护。
原文地址: https://www.cveoy.top/t/topic/pLkw 著作权归作者所有。请勿转载和采集!