一个长度为n的数组中有重复的数字,有多少个重复的或者重复多少次都不清楚,每个数字的值在0~n-1之间,找出任意重复的数字。
这个问题还是比较简单的,由于所有数字的值都在数组下标的范围内,所以遍历一遍数组,对于每个值,把相应下标的值加n,使其大于n-1,第二次访问到这个下标就能知道该值重复了。时间复杂度为O(n)。
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
if(numbers == null||numbers.length == 0||length <= 0)
return false;
for(int i = 0;i < length;i++){
if(numbers[numbers[i]%length] > length-1){
duplication[0] = numbers[i]%length;
return true;
}else{
numbers[numbers[i]%length] += length;
}
}
return false;
}
}
这样空间复杂度为常数,不过会破坏原数组;另一种办法是新建一个数组保存标志位,这样不会破坏原数组,但是空间复杂度为O(n)。