You have been given an integer array/list(ARR) of size N. Where N is equal to [2M + 1].
Now, in the given array/list, 'M' numbers are present twice and one number is present only once.
You need to find and return that number which is unique in the array/list.
Sample Input 1:
7
2 3 1 6 3 6 2
Sample Output 1:
1
Approach 1 - > (Using XOR)
package CodingNinjas;
import java.util.Scanner;
public class FindUnique {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int b= findUnique(a);
System.out.println(b);
}
public static int findUnique(int[] arr){
int l=arr.length;
int ele=0;
for(int i=0;i<l;i++)
{
// if we do XOR of same elements we get 0 i.e 5^5 => 101 ^ 101 = 000
ele^=arr[i];
}
return ele;
}
}
Approach 2 -
public static int findUnique(int[] arr){
int l= arr.length;
for(int i=0;i<l;i++)
{
int j;
for(j=0;j<l;j++)
{
if(i!=j)
{
if(arr[i]==arr[j])
{
break;
}
}
}
if(j==l)
{
return arr[i];
}
}
return Integer.MAX_VALUE;
}
}
Comments
Post a Comment