题目:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
思路:
将数组元素对应的下表存放对应的元素,如果不满足,则进行交换。
class Solution {
public:
// duplication--- 指的是重复元素
// 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) {
//数组为空或者传入的数组长度为小于等于0
if (numbers == NULL || length <= 0)
return false;
//数组元素超出范围
for (int i = 0; i<length; ++i)
{
if (numbers[i]<0 || numbers[i]>length - 1)
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
{
//交换numbers[i]和numbers[numbers[i]]
int tmp = numbers[i];
numbers[i] = numbers[tmp];
numbers[tmp] = tmp;
}
}
}
return false;
}
};