題目描述
在一個長度為n的數(shù)組里的所有數(shù)字都在0到n-1的范圍內(nèi)扩然。 數(shù)組中某些數(shù)字是重復(fù)的,但不知道有幾個數(shù)字是重復(fù)的聋伦。也不知道每個數(shù)字重復(fù)幾次夫偶。請找出數(shù)組中任意一個重復(fù)的數(shù)字界睁。 例如,如果輸入長度為7的數(shù)組{2,3,1,0,2,5,3}索守,那么對應(yīng)的輸出是重復(fù)的數(shù)字2或者3晕窑。
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(length<=0||duplication==NULL)
return false;
for(int i=0;i<length;i++)
{
if(numbers[i]<0||numbers[i]>=length)
return false;
}
for(int i=0;i<length;i++)
{
while(numbers[i]!=i)
{
if(numbers[i]==numbers[numbers[i]])
{
*duplication = numbers[i];
return true;
}
else
swap(numbers[i],numbers[numbers[i]]);
}
}
return false;
}
};