查找整数数组中第一个重复元素(C++)
在这个问题中,我们有一个包含 n 个整数值的数组 arr。我们的任务是查找整数数组中第一个重复元素。
我们需要找到数组中第一个出现不止一次的整数值。
让我们举个例子来理解这个问题,
Input : arr[] = {4, 1, 8, 9, 7, 2, 1, 6, 4}
Output : 4说明 −
Integers with more than one occurrence are 4 and 1. 4's first occurrence is smaller than 1. Hence the answer is 4
解决方案方法
解决这个问题的一个简单方法是使用嵌套循环。我们将使用两个循环,外部循环迭代数组的每个整数值,内部循环检查数组中是否存在另一个具有相同值的整数值。如果是,则返回该值。这种方法很好,但在没有解决方案的情况下,其复杂度将为 O(N2)。
解决方案方法
另一种可以更好地解决问题的方案是使用哈希表。我们将从最后一个索引遍历数组,然后更新在访问的索引处找到的元素的最小索引。
示例
程序说明解决方案的工作原理
#include<bits/stdc++.h>
using namespace std;
int findRepeatingElementArray(int arr[], int n){
int minRetIndex = -1;
set<int> visitedElements;
for (int i = n - 1; i >= 0; i--){
if (visitedElements.find(arr[i]) != visitedElements.end())
minRetIndex = i;
else
visitedElements.insert(arr[i]);
}
if (minRetIndex != -1)
return arr[minRetIndex];
else
return -1;
}
int main(){
int arr[] = {4, 1, 6, 3, 4, 1, 5, 8};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The element with repeated occurence is "<<findRepeatingElementArray(arr, n);
}输出
The element with repeated occurence is 4
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP