题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
题目分析
这道题可以通过比较当前位置下的值和该值为索引的值比较,从而使得时间复杂度为O(n) ,空间复杂度为O(1)
代码演示
public boolean duplicate(int numbers[],int length,int [] duplication) {
//边界值判断
if (numbers == null || numbers.length == 0){
duplication[0] = -1;
return false;
}
//循环列表 判断当前位置的值是否与对应索引值相等
for(int i = 0;i < length ; i++){
//如果不等的话
while(numbers[i] != i){
// 判断该值与该值为索引的值时候相等
if (numbers[i] == numbers[numbers[i]]){
// 如果相等则返回
duplication[0] = numbers[i];
return true;
}
//否则交换
int temp = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = temp;
}
}
return false;
} 
京公网安备 11010502036488号