思路總結(jié):
每一次將不合適numbers[i]換到自己的位置去,也就是每次遍歷會(huì)有一個(gè)位置歸為成功丧叽,如果要去的位置已經(jīng)有了相匹配的數(shù)字卫玖,說(shuō)明重復(fù)。
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 == nullptr || length < 0)
return false;
for(int i = 0;i < length; i++){
if(numbers[i] >= length || numbers[i] < 0)
return false;
}
for(int i = 0; i < length; i++){
while(i != numbers[i]){
if(numbers[i] == numbers[numbers[i]]){
*duplication = numbers[i];
return true;
}
int tmp = numbers[i];
numbers[i] = numbers[tmp];
numbers[tmp] = tmp;
}
}
return false;
}
};
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) {
int i = 0;
while(i < length){
int value = numbers[i];
if(value == i){
i++;
continue;
}
if(numbers[value] == value){
*duplication = value;
return true;
}
else{
swap(numbers[i], numbers[value]);
continue;
}
i++;
}
return false;
}
};