给定一个整数数组,在其中找到第一个重复元素。我们需要找到多次出现并且第一次出现的索引最小的元素。
例子:
Input: arr[] = {10, 5, 3, 4, 3, 5, 6}
Output: 5 [5 is the first element that repeats]
Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}
Output: 6 [6 is the first element that repeats]
一个简单的解决方案是使用两个嵌套循环。外循环一个接一个地选择一个元素,内循环检查该元素是否重复。找到重复的元素后,我们将中断循环并打印该元素。该解决方案的时间复杂度为O(n 2 )
我们可以使用排序来解决O(nLogn)时间中的问题。以下是详细步骤。
1)将给定的数组复制到辅助数组temp []。
2)使用O(nLogn)时间排序算法对临时数组进行排序。
3)从左到右扫描输入阵列。对于每个元素,使用二进制搜索在temp []中计算其出现次数。一旦发现一个元素出现多次,我们将返回该元素。此步骤可以在O(nLogn)时间完成。
我们可以使用散列来平均解决O(n)时间。这个想法是从右到左遍历给定的数组,并在我们找到在右侧访问过的元素时更新最小索引。感谢Mohammad Shahid提出了此解决方案。
以下是该想法的实现。
C++
/* C++ program to find first repeating element in arr[] */
#include
using namespace std;
// This function prints the first repeating element in arr[]
void printFirstRepeating(int arr[], int n)
{
// Initialize index of first repeating element
int min = -1;
// Creates an empty hashset
set myset;
// Traverse the input array from right to left
for (int i = n - 1; i >= 0; i--)
{
// If element is already in hash set, update min
if (myset.find(arr[i]) != myset.end())
min = i;
else // Else add element to hash set
myset.insert(arr[i]);
}
// Print the result
if (min != -1)
cout << "The first repeating element is " << arr[min];
else
cout << "There are no repeating elements";
}
// Driver method to test above method
int main()
{
int arr[] = {10, 5, 3, 4, 3, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printFirstRepeating(arr, n);
}
//This article is contributed by Chhavi
Java
/* Java program to find first repeating element in arr[] */
import java.util.*;
class Main
{
// This function prints the first repeating element in arr[]
static void printFirstRepeating(int arr[])
{
// Initialize index of first repeating element
int min = -1;
// Creates an empty hashset
HashSet set = new HashSet<>();
// Traverse the input array from right to left
for (int i=arr.length-1; i>=0; i--)
{
// If element is already in hash set, update min
if (set.contains(arr[i]))
min = i;
else // Else add element to hash set
set.add(arr[i]);
}
// Print the result
if (min != -1)
System.out.println("The first repeating element is " + arr[min]);
else
System.out.println("There are no repeating elements");
}
// Driver method to test above method
public static void main (String[] args) throws java.lang.Exception
{
int arr[] = {10, 5, 3, 4, 3, 5, 6};
printFirstRepeating(arr);
}
}
Python3
# Python3 program to find first repeating
# element in arr[]
# This function prints the first repeating
# element in arr[]
def printFirstRepeating(arr, n):
# Initialize index of first repeating element
Min = -1
# Creates an empty hashset
myset = dict()
# Traverse the input array from right to left
for i in range(n - 1, -1, -1):
# If element is already in hash set,
# update Min
if arr[i] in myset.keys():
Min = i
else: # Else add element to hash set
myset[arr[i]] = 1
# Print the result
if (Min != -1):
print("The first repeating element is",
arr[Min])
else:
print("There are no repeating elements")
# Driver Code
arr = [10, 5, 3, 4, 3, 5, 6]
n = len(arr)
printFirstRepeating(arr, n)
# This code is contributed by Mohit kumar 29
C#
using System;
using System.Collections.Generic;
/* C# program to find first repeating element in arr[] */
public class GFG
{
// This function prints the first repeating element in arr[]
public static void printFirstRepeating(int[] arr)
{
// Initialize index of first repeating element
int min = -1;
// Creates an empty hashset
HashSet set = new HashSet();
// Traverse the input array from right to left
for (int i = arr.Length - 1; i >= 0; i--)
{
// If element is already in hash set, update min
if (set.Contains(arr[i]))
{
min = i;
}
else // Else add element to hash set
{
set.Add(arr[i]);
}
}
// Print the result
if (min != -1)
{
Console.WriteLine("The first repeating element is " + arr[min]);
}
else
{
Console.WriteLine("There are no repeating elements");
}
}
// Driver method to test above method
public static void Main(string[] args)
{
int[] arr = new int[] {10, 5, 3, 4, 3, 5, 6};
printFirstRepeating(arr);
}
}
// This code is contributed by Shrikant13
C++
/* C++ program to find first
repeating element in arr[] */
#include
using namespace std;
// This function prints the
// first repeating element in arr[]
void printFirstRepeating(int arr[], int n)
{
// This will set k=1, if any
// repeating element found
int k = 0;
// max = maximum from (all elements & n)
int max = n;
for (int i = 0; i < n; i++)
if (max < arr[i])
max = arr[i];
// Array a is for storing
// 1st time occurence of element
// initialized by 0
int a[max + 1] = {};
// Store 1 in array b
// if element is duplicate
// initialized by 0
int b[max + 1] = {};
for (int i = 0; i < n; i++)
{
// Duplicate element found
if (a[arr[i]])
{
b[arr[i]] = 1;
k = 1;
continue;
}
else
// storing 1st occurence of arr[i]
a[arr[i]] = i;
}
if (k == 0)
cout << "No repeating element found" << endl;
else
{
int min = max + 1;
// trace array a & find repeating element
// with min index
for (int i = 0; i < max + 1; i++)
if (a[i] && min > a[i] && b[i])
min = a[i];
cout << arr[min];
}
cout << endl;
}
// Driver method to test above method
int main()
{
int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
printFirstRepeating(arr, n);
}
Java
/* Java program to find first
repeating element in arr[] */
public class GFG
{
// This function prints the
// first repeating element in arr[]
static void printFirstRepeating(int[] arr, int n)
{
// This will set k=1, if any
// repeating element found
int k = 0;
// max = maximum from (all elements & n)
int max = n;
for (int i = 0; i < n; i++)
if (max < arr[i])
max = arr[i];
// Array a is for storing
// 1st time occurence of element
// initialized by 0
int[] a = new int[max + 1];
// Store 1 in array b
// if element is duplicate
// initialized by 0
int[] b = new int[max + 1];
for (int i = 0; i < n; i++)
{
// Duplicate element found
if (a[arr[i]] != 0)
{
b[arr[i]] = 1;
k = 1;
continue;
}
else
// storing 1st occurence of arr[i]
a[arr[i]] = i;
}
if (k == 0)
System.out.println("No repeating element found");
else
{
int min = max + 1;
// trace array a & find repeating element
// with min index
for (int i = 0; i < max + 1; i++)
if (a[i] != 0 && min > a[i] && b[i] != 0)
min = a[i];
System.out.print(arr[min]);
}
System.out.println();
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.length;
printFirstRepeating(arr, n);
}
}
// This code is contributed by divyesh072019
Python3
# Python3 program to find first
# repeating element in arr[]
# This function prints the
# first repeating element in arr[]
def printFirstRepeating(arr, n):
# This will set k=1, if any
# repeating element found
k = 0
# max = maximum from (all elements & n)
max = n
for i in range(n):
if (max < arr[i]):
max = arr[i]
# Array a is for storing
# 1st time occurence of element
# initialized by 0
a = [0 for i in range(max + 1)]
# Store 1 in array b
# if element is duplicate
# initialized by 0
b = [0 for i in range(max + 1)]
for i in range(n):
# Duplicate element found
if (a[arr[i]]):
b[arr[i]] = 1
k = 1
continue
else:
# Storing 1st occurence of arr[i]
a[arr[i]] = i
if (k == 0):
print("No repeating element found")
else:
min = max + 1
for i in range(max + 1):
# Trace array a & find repeating
# element with min index
if (a[i] and (min > (a[i])) and b[i]):
min = a[i]
print(arr[min])
# Driver code
arr = [ 10, 5, 3, 4, 3, 5, 6 ]
n = len(arr)
printFirstRepeating(arr, n)
# This code is contributed by avanitrachhadiya2155
C#
/* C# program to find first
repeating element in arr[] */
using System;
class GFG
{
// This function prints the
// first repeating element in arr[]
static void printFirstRepeating(int[] arr, int n)
{
// This will set k=1, if any
// repeating element found
int k = 0;
// max = maximum from (all elements & n)
int max = n;
for (int i = 0; i < n; i++)
if (max < arr[i])
max = arr[i];
// Array a is for storing
// 1st time occurence of element
// initialized by 0
int[] a = new int[max + 1];
// Store 1 in array b
// if element is duplicate
// initialized by 0
int[] b = new int[max + 1];
for (int i = 0; i < n; i++)
{
// Duplicate element found
if (a[arr[i]] != 0)
{
b[arr[i]] = 1;
k = 1;
continue;
}
else
// storing 1st occurence of arr[i]
a[arr[i]] = i;
}
if (k == 0)
Console.WriteLine("No repeating element found");
else
{
int min = max + 1;
// trace array a & find repeating element
// with min index
for (int i = 0; i < max + 1; i++)
if ((a[i] != 0) && min > a[i] && (b[i] != 0))
min = a[i];
Console.Write(arr[min]);
}
Console.WriteLine();
}
// Driver code
static void Main()
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.Length;
printFirstRepeating(arr, n);
}
}
// This code is contributed by divyeshrabadiya07.
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static int firstRepeated(int[] arr, int n)
{
int max = 0;
for (int x = 0; x < n; x++) {
if (arr[x] > max) {
max = arr[x];
}
}
int temp[]
= new int[max + 1]; // the idea is to use
// temporary array as hashmap
Arrays.fill(temp, 0);
for (int x = 0; x < n; x++) {
int num = arr[x];
temp[num]++;
}
for (int x = 0; x < n; x++) {
int num = arr[x];
if (temp[num] > 1) {
return x;
}
}
return -1; // if no repeating element found
}
public static void main(String[] args)
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.length;
int index = firstRepeated(
arr,
arr.length); // index Of 1st repeating number
if (index != -1) {
System.out.println("1st Repeatig Number is "
+ arr[index]);
}
else {
System.out.println("No Repeating Number Found");
}
}
}
Python3
# Python3 program to find first
# repeating element in arr[]
# This function prints the
# first repeating element in arr[]
def printFirstRepeating(a, n):
for i in range(len(a)):
if a.count(a[i]) > 1:
return a[i]
return "there is no repetition number"
# Driver code
arr = [10, 5, 3, 4, 3, 5, 6]
n = len(arr)
print(printFirstRepeating(arr, n))
# This code is contributed by karthikeyakumarnallam
输出
The first repeating element is 5
另一种方法:
如果要执行此操作而不使用任何其他数据结构。仅使用数组也可以解决该问题。请参阅下面的方法。
C++
/* C++ program to find first
repeating element in arr[] */
#include
using namespace std;
// This function prints the
// first repeating element in arr[]
void printFirstRepeating(int arr[], int n)
{
// This will set k=1, if any
// repeating element found
int k = 0;
// max = maximum from (all elements & n)
int max = n;
for (int i = 0; i < n; i++)
if (max < arr[i])
max = arr[i];
// Array a is for storing
// 1st time occurence of element
// initialized by 0
int a[max + 1] = {};
// Store 1 in array b
// if element is duplicate
// initialized by 0
int b[max + 1] = {};
for (int i = 0; i < n; i++)
{
// Duplicate element found
if (a[arr[i]])
{
b[arr[i]] = 1;
k = 1;
continue;
}
else
// storing 1st occurence of arr[i]
a[arr[i]] = i;
}
if (k == 0)
cout << "No repeating element found" << endl;
else
{
int min = max + 1;
// trace array a & find repeating element
// with min index
for (int i = 0; i < max + 1; i++)
if (a[i] && min > a[i] && b[i])
min = a[i];
cout << arr[min];
}
cout << endl;
}
// Driver method to test above method
int main()
{
int arr[] = { 10, 5, 3, 4, 3, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
printFirstRepeating(arr, n);
}
Java
/* Java program to find first
repeating element in arr[] */
public class GFG
{
// This function prints the
// first repeating element in arr[]
static void printFirstRepeating(int[] arr, int n)
{
// This will set k=1, if any
// repeating element found
int k = 0;
// max = maximum from (all elements & n)
int max = n;
for (int i = 0; i < n; i++)
if (max < arr[i])
max = arr[i];
// Array a is for storing
// 1st time occurence of element
// initialized by 0
int[] a = new int[max + 1];
// Store 1 in array b
// if element is duplicate
// initialized by 0
int[] b = new int[max + 1];
for (int i = 0; i < n; i++)
{
// Duplicate element found
if (a[arr[i]] != 0)
{
b[arr[i]] = 1;
k = 1;
continue;
}
else
// storing 1st occurence of arr[i]
a[arr[i]] = i;
}
if (k == 0)
System.out.println("No repeating element found");
else
{
int min = max + 1;
// trace array a & find repeating element
// with min index
for (int i = 0; i < max + 1; i++)
if (a[i] != 0 && min > a[i] && b[i] != 0)
min = a[i];
System.out.print(arr[min]);
}
System.out.println();
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.length;
printFirstRepeating(arr, n);
}
}
// This code is contributed by divyesh072019
Python3
# Python3 program to find first
# repeating element in arr[]
# This function prints the
# first repeating element in arr[]
def printFirstRepeating(arr, n):
# This will set k=1, if any
# repeating element found
k = 0
# max = maximum from (all elements & n)
max = n
for i in range(n):
if (max < arr[i]):
max = arr[i]
# Array a is for storing
# 1st time occurence of element
# initialized by 0
a = [0 for i in range(max + 1)]
# Store 1 in array b
# if element is duplicate
# initialized by 0
b = [0 for i in range(max + 1)]
for i in range(n):
# Duplicate element found
if (a[arr[i]]):
b[arr[i]] = 1
k = 1
continue
else:
# Storing 1st occurence of arr[i]
a[arr[i]] = i
if (k == 0):
print("No repeating element found")
else:
min = max + 1
for i in range(max + 1):
# Trace array a & find repeating
# element with min index
if (a[i] and (min > (a[i])) and b[i]):
min = a[i]
print(arr[min])
# Driver code
arr = [ 10, 5, 3, 4, 3, 5, 6 ]
n = len(arr)
printFirstRepeating(arr, n)
# This code is contributed by avanitrachhadiya2155
C#
/* C# program to find first
repeating element in arr[] */
using System;
class GFG
{
// This function prints the
// first repeating element in arr[]
static void printFirstRepeating(int[] arr, int n)
{
// This will set k=1, if any
// repeating element found
int k = 0;
// max = maximum from (all elements & n)
int max = n;
for (int i = 0; i < n; i++)
if (max < arr[i])
max = arr[i];
// Array a is for storing
// 1st time occurence of element
// initialized by 0
int[] a = new int[max + 1];
// Store 1 in array b
// if element is duplicate
// initialized by 0
int[] b = new int[max + 1];
for (int i = 0; i < n; i++)
{
// Duplicate element found
if (a[arr[i]] != 0)
{
b[arr[i]] = 1;
k = 1;
continue;
}
else
// storing 1st occurence of arr[i]
a[arr[i]] = i;
}
if (k == 0)
Console.WriteLine("No repeating element found");
else
{
int min = max + 1;
// trace array a & find repeating element
// with min index
for (int i = 0; i < max + 1; i++)
if ((a[i] != 0) && min > a[i] && (b[i] != 0))
min = a[i];
Console.Write(arr[min]);
}
Console.WriteLine();
}
// Driver code
static void Main()
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.Length;
printFirstRepeating(arr, n);
}
}
// This code is contributed by divyeshrabadiya07.
输出
5
时间复杂度: O(n)。
使用O(n)辅助空间和O(n)时间复杂度的另一种方法:
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static int firstRepeated(int[] arr, int n)
{
int max = 0;
for (int x = 0; x < n; x++) {
if (arr[x] > max) {
max = arr[x];
}
}
int temp[]
= new int[max + 1]; // the idea is to use
// temporary array as hashmap
Arrays.fill(temp, 0);
for (int x = 0; x < n; x++) {
int num = arr[x];
temp[num]++;
}
for (int x = 0; x < n; x++) {
int num = arr[x];
if (temp[num] > 1) {
return x;
}
}
return -1; // if no repeating element found
}
public static void main(String[] args)
{
int[] arr = { 10, 5, 3, 4, 3, 5, 6 };
int n = arr.length;
int index = firstRepeated(
arr,
arr.length); // index Of 1st repeating number
if (index != -1) {
System.out.println("1st Repeatig Number is "
+ arr[index]);
}
else {
System.out.println("No Repeating Number Found");
}
}
}
使用Python内置函数的另一种方法:
Python3
# Python3 program to find first
# repeating element in arr[]
# This function prints the
# first repeating element in arr[]
def printFirstRepeating(a, n):
for i in range(len(a)):
if a.count(a[i]) > 1:
return a[i]
return "there is no repetition number"
# Driver code
arr = [10, 5, 3, 4, 3, 5, 6]
n = len(arr)
print(printFirstRepeating(arr, n))
# This code is contributed by karthikeyakumarnallam
输出
5