n elements are same in a array

Given an array of 2n elements of which n elements are same and the
remaining n elements are all different. Write a C program to find out the
value which is present n times in the array.

Solution:

1. Sort the array - O(nlog(n))
2. Linear algo to find the dup:

for(int i = 0, j=i+1; j < 2n; ++j)
{
if( a[j] != a[i] )
{
if ( (j-i) == n )
/* a[i] is the required number */
else
{
/* proceed further */
i = j;
j+= 1;
}
}
}

No comments: