在 C++ 中的只读数组中查找多个重复元素中的任何一个
在本教程中,我们将编写一个程序来查找给定数组中的重复元素。
让我们看看解决问题的步骤。
初始化数组。
初始化一个计数器映射来存储数组中每个元素的频率。
遍历数组。
计算每个元素。
打印频率大于1的元素。
示例
让我们看看代码。
#include输出结果using namespace std; int findRepeatingElement(int arr[], int n) { map frequencies; for (int i = 0; i < n; i++) { map ::iterator itr = frequencies.find(arr[i]); if (itr != frequencies.end()) { itr->second = itr->second + 1; } else { frequencies.insert({arr[i], 1}); } } for (map ::iterator itr = frequencies.begin(); itr != frequencies.end(); ++itr) { if (itr->second > 1) { return itr->first; } } } int main() { int arr[] = {1, 2, 3, 3, 4, 5, 5, 6}; cout << findRepeatingElement(arr, 8) << endl; return 0; }
如果你运行上面的代码,那么你会得到下面的结果
3
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下