Dec 27, 2008

Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array i

Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.
N number has n msb, we take these msbs as bit vector to check the duplicate number

bool func(int* a, int len) //len=n+1
{
for(int i=1;i<len;i++)
{
int idx=a[i]<0?(-1*a[i]):a[i];
if(a[idx]<0) {cout<<"duplicate "<<-1*a[idx]<<endl;
return false; }
a[idx]*=-1;
}
return true;
}

No comments:

Post a Comment