Missing number in Array
Simple approach is to add all elements of array 1 and then subtract all elements from sum , remaining will be missed element.
Idea is to do XOR of all the elements and again xor with n-1 elements , remaining will be the missing number.(Twice xor of same number is 0)
Code:
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int xor=0;
//first array
for(int i=0;i<n;i++)
xor^=ab.nextInt();
//second array with 1 element missing
for(int i=0;i<n-1;i++)
xor^=ab.nextInt();
System.out.println(xor);
}
}
0 Comments:
Post a Comment