在 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

结论

如果您对本教程有任何疑问,请在评论部分提及。