题解
- 最简单的方法是hash或者set,遍历即可
- 由于所有数字范围都是 [ 0 , n − 1 ] [0, n-1] [0,n−1]
- 所以每个数字都有属于自己的位置
- 那么就把不在自己位置的数每个数方到自己的位置,如果该位置已经占用了,就说明有重复。
AC-Code
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) return false;
for(int i = 0; i < length; ++i) {
while(i != numbers[i])
if(numbers[i] == numbers[numbers[i]]) {
*duplication = numbers[i];
return true;
}
else
swap(numbers[i], numbers[numbers[i]]);
}
return false;
}
};