Find the first repeating element in an array of integers
Time Complexity O(n)
This problem can be solved by the vector also the only difference is that you have to replace the add method with the addElement() method and import Vector.
The only main difference between the ArrayList and Vector is that Vector is thread safe but the ArrayList is not.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class ArrayList1
{
public static void main(String[] args)
{
int i;
int [] arr=new int[30];
System.out.println("Enter the size of the array\n");
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
ArrayList <Integer> al= new ArrayList<Integer>();
for(i=0;i<n;i++)
{
if(al.contains(arr[i]))
{
System.out.println("The first repeated element in the array is "+arr[i]);
break;
}
else
{
al.add(arr[i]);
}
}
}
}
No comments:
Post a Comment