题目
题目一:找出数组中重复的数字。
在一个长度为 n 的数组里的所有数字都在 0 ~ n-1 的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为 7 的数组 {2, 3, 1, 0, 2, 5, 3},那么对应的输出是重复的数字 2 或者 3。
分析
代码
public class RepeatNumber {
public static void main(String[] args) {
int[] array = {5, 12, 12, 0, 4, 2, 3};
int i = searchRepeat(array);
System.out.println(i);
}
private static int searchRepeat(int[] array) {
if (array.length <= 0 || array == null) {
return 0;
}
for (int i = 0; i < array.length; i++) {
while (i != array[i]) {
int temp = array[i];
if (array[temp] == array[i]) {
return temp;
} else {
int tempData = array[temp];
array[temp] = array[i];
array[i] = tempData;
}
}
}
return 0;
}
}
题目
题目二:不修改数组找出重复的数字。
在一个长度为 n+1 的数组里的所有数字都在 1~n 的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如:如果输入长度为 8 的数组 {2, 3, 5, 4, 3, 2, 6, 7},那么对应的输出是重复的数字 2 或者 3。
分析一
可以将原来的数组复制到一个新的数组中,如果原数组中被复制的数字是 m,就把它复制到新数组的下标为 m 的位置。但是该方案需要 O(n) 的辅助空间。
代码一
public class RepeatNumber2 {
public static void main(String[] args) {
int[] array = {1, 3, 5, 4, 3, 2, 6, 7};
int i = searchRepeat(array);
System.out.println(i);
}
public static int searchRepeat(int[] array) {
if (array.length <= 0) {
return 0;
}
int[] arrayCopy = new int[array.length];
for (int i = 0; i < array.length; i++) {
int temp = array[i];
if (temp != arrayCopy[temp]) {
arrayCopy[temp] = temp;
}
return temp;
}
return 0;
}
}
分析二
可以使用二分查找法。
代码二
public class RepeatNumber2_2 {
public static void main(String[] args) {
int[] array = {6, 6, 5, 4, 3, 2, 6, 7};
int i = searchRepeat(array);
System.out.println(i);
}
public static int searchRepeat(int[] array) {
if (array.length <= 0) {
return 0;
}
int left = 1;
int right = array.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
int count = countRange(array, left, mid);
if (left == right) {
if (count > 1) {
return left;
} else {
break;
}
}
if (count > (mid - left + 1)) {
right = mid;
} else {
left = mid + 1;
}
}
return 0;
}
public static int countRange(int[] array, int left, int right) {
if (array.length <= 0) {
return 0;
}
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] >= left && array[i] <= right) {
count++;
}
}
return count;
}
}