题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
题目分析
注意题目条件长度为n的数组,范围在0~n-1。
已知数组中的每一个数字值小于数组长度,如果数组中无任何重复的数字,则数组从小到大排序后理应满足第i个位置对应的元素值是i。利用此特性(数组{2, 3, 1, 0, 2, 5, 3},指针’|’):
|2 3 1 0 2 5 3
指针’|'此时的位置是0,而数组中位置0的元素值是2,2 != 0,将数组中位置0与位置2的元素相互交换。
|1 3 2 0 2 5 3
指针’|'的位置依然是0,而数组中位置0的元素值是1,1 != 0,将数组中位置0与位置1的元素相互交换。
|3 1 2 0 2 5 3
指针’|'的位置依然是0,而数组中位置0的元素值是3,3 != 0,将数组中位置0与位置3的元素相互交换。
|0 1 2 3 2 5 3
指针’|‘的位置依然是0,但数组中位置0的元素值是0,0 == 0,将指针’|'右移一位。
0 |1 2 3 2 5 3
指针’|‘此时的位置是1,但数组中位置1的元素值是1,1 == 1,将指针’|'右移一位。
0 1 |2 3 2 5 3
指针’|‘此时的位置是2,但数组中位置2的元素值是2,2 == 2,将指针’|'右移一位。
0 1 2 |3 2 5 3
指针’|‘此时的位置是3,但数组中位置3的元素值是3,3 == 3,将指针’|'右移一位。
0 1 2 3 |2 5 3
指针’|'此时的位置是4,而数组中位置4的元素值是2,2 != 4,且数组中位置4与位置2的元素值相等,那么输出此元素值。
代码
C++代码如下:
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(numbers==0||length==0)
return false;
for(int i=0;i<length;i++)//指针在初始位置0
{
while(numbers[i]!=i)//当数组第i位置的元素不为i时
{
if(numbers[i]==numbers[numbers[i]])//数组第i位置的值A = 第A位置的值
{
*duplication=numbers[i];
return true;
}
else//否则,交换两个位置的元素
{
int temp=numbers[i];
numbers[i]=numbers[temp];
numbers[temp]=temp;
}
}
}
return false;
}
};