在 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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短