20180910更新。利用数组做一次hash映射,时间复杂度为 O(n) O ( n ) ,空间复杂度 O(n) O ( n ) .
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 hash[length];
memset(hash, 0, sizeof(hash));
for (int i = 0; i < length; i++) {
hash[numbers[i]]++;
if (hash[numbers[i]] >= 2) {
*duplication = numbers[i];
return true;
}
}
return false;
}
};
参考网址:https://www.nowcoder.com/profile/4747275/codeBookDetail?submissionId=16801123
思路:不需要额外的数组或者hash table来保存,题目里写了数组里数字的范围保证在0 ~ n-1 之间,所以可以利用现有数组设置标志,当一个数字被访问过后,可以设置对应位上的数 + n,之后再遇到相同的数时,会发现对应位上的数已经大于等于n了,那么直接返回这个数即可。
点评:对于此类问题很好的思路。值得特殊记一下!
时间复杂度 O(n) O ( n ) ,空间复杂度 O(1) O ( 1 ) .
20180910晚:思路确实巧妙啊~~~
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 index;
for(int i = 0; i < length; i++) {
index = numbers[i];
if(index >= length) {
index -= length;
}
if(numbers[index] > length) {
*duplication = index;
return true;
}
numbers[index] += length;
}
return false;
}
};