之前看过一遍剑指offer这本书,但买的这本书是用C++实现的,现在想用Java把上面的题重新实现一遍,刷题的方法是看一下书本上的思路尝试自己写出来然后在牛客网上测试样例,下面的代码都是完整地通过了所有的测试样例。
第一题:一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
public static boolean duplicate(int numbers[],int length,int [] duplication) {
if (numbers == null|| length == 0){
return false;
}
for (int number:numbers){
if (number < 0||number > length-1)
return false;
}
for (int i =0;i<length;i++){
while (numbers[i] != i) {
int j = numbers[i];
if (j != i) {
int temp = numbers[j];
if (temp == j) {
duplication[0] = j;
return true;
}
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
if (duplication == null){
return false;
}
return false;
}
public static void main(String[] args) {
int[] numbers = {2,1,3,0,4};
int length = numbers.length;
int[] duplicate = new int[length];
Boolean flag = duplicate(numbers,length,duplicate);
if (flag){
System.out.println(duplicate[0]);
}
}