Given a list of numbers, such that all but one element occurs more than once in the list. Find the element that occurs only once.
This is Java implementation:
package competitiveprograming;
import java.util.*;
public class FindSingleInArray {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter size of array");
int size=sc.nextInt();
System.out.print("Enter an element where one of the element will not repeat again..");
int arr[]= new int[10];
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
List<Integer> no_duplicate_list= new ArrayList<Integer>();
for(int j : arr)
{
if(!no_duplicate_list.contains(j))
{
no_duplicate_list.add(j);
}
else
{
no_duplicate_list.remove(j);
}
}
System.out.print(no_duplicate_list.get(0));
sc.close();
}
}
And this is the error message I'm getting:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.remove(ArrayList.java:502)
at competitiveprograming/competitiveprograming.FindSingleInArray.main(FindSingleInArray.java:28)