在 C++ 的只读数组中查找任意一个重复元素
在本教程中,我们将编写一个程序,该程序将在给定的数组中找到重复元素。
让我们来看看解决该问题的步骤。
初始化数组。
初始化计数器映射,用于存储数组中每个元素的频率。
遍历数组。
统计每个元素。
打印频率大于 1 的元素。
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
int findRepeatingElement(int arr[], int n) {
map<int, int> frequencies;
for (int i = 0; i < n; i++) {
map<int, int>::iterator itr = frequencies.find(arr[i]);
if (itr != frequencies.end()) {
itr->second = itr->second + 1;
}
else {
frequencies.insert({arr[i], 1});
}
}
for (map<int, int>::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
结论
如果您对本教程有任何疑问,请在评论部分中提及。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP