在整数数组中找到第一个重复元素
时间:2020-02-23 14:34:10 来源:igfitidea点击:
在本教程中,我们将看到如何在整数数组中找到第一个重复元素。
问题
在整数数组中找到第一个重复元素。
例如:
Input: array[] = {10, 7, 8, 1, 8, 7, 6}
Output: 7 [7 is the first element actually repeats]
解决方案
简单的解决方案将使用两个环。
外循环将迭代循环,内循环将检查元素是否重复,但此解决方案的时间复杂度将是O(n ^ 2)。
另一个解决方案是创建另一个数组并对其进行排序。
从原始数组中查看元素,并使用二进制搜索找到排序阵列中的元素,但此解决方案的时间复杂度将是O(n ^ logn)。
我们可以做得更好吗?
是的,我们可以从右到左右迭代,并使用Hashset来跟踪FineinIndex
- 用-1 intialize finestIndex
- 从右到左迭代输入数组
- 如果元素已存在于hashset中,则将FinestIndIndex eldent元素更新为集合
- 一旦我们完成迭代,我们将在最后获取Final线索
程序找到一个整数数组中的第一个重复元素
package org.igi.theitroad;
/* Java program to find first repeating element in arr[] */
import java.util.*;
public class FirstRepatingElementMain
{
//This function prints the first repeating element in arr[]
static int getFirstRepeatingElementArray(int array[])
{
//Initialize index of first repeating element
int minimumIndex = -1;
//Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
//Iterate over the input array from right to left
for (int i=array.length-1; i>=0; i--)
{
//If set contains the element, update minimum index
if (set.contains(array[i]))
minimumIndex = i;
else //Else add element to hash set
set.add(array[i]);
}
return minimumIndex;
}
public static void main (String[] args) throws java.lang.Exception
{
int array[] = {10, 7, 8, 1, 8, 7, 6};
int min=getFirstRepeatingElementArray(array);
//Print the result
if (min != -1)
System.out.println("The first repeating element in array is " + array[min]);
else
System.out.println("There are no repeating elements");
}
}
运行上面的程序时,我们将得到以下输出:
The first repeating element in array is 7
该解决方案的时间复杂性是O(n),并且空间复杂性也是O(n)。

