思路总结:
每一次将不合适numbers[i]换到自己的位置去,也就是每次遍历会有一个位置归为成功,如果要去的位置已经有了相匹配的数字,说明重复。
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;
}
};