描述:在一个长度为n+1的数组里的所有数字都在1~n的范围内,所以数组中至少有一个是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3。
这道题跟 面试题:数组中重复的数字 基本一样,但是限制了不能修改输入数组。
思路1:创建一个n+1的辅助数组,然后逐一把原数组的每个数字复制到辅助数组。如果原数组中的数字为m,则复制到辅助数组中下标为m的位置。很容易就能发现哪个数字是重复的。该方法需要O(n)的辅助空间。
package com.cb.java.algorithms.jianzhioffer;
public class DuplicateWithNoChangeInArray {
private static int findDuplicateNum(int[] numbers) {
int length = numbers.length;
if (numbers == null || length <= 0)
return -1;
for (int i : numbers) {
if (i <= 0|| i >= length)
return -1;
}
int[] temp = new int[length];// 开辟一个新的数组
for (int i : numbers) {
if (temp[i] > 0)
return temp[i];
else
temp[i] = i;
}
return -1;
}
public static void main(String[] args) {
int[] numbers = { 2, 3, 5, 4, 3, 2, 6, 7 };
int dup = findDuplicateNum(numbers);
System.out.println(dup);
}
}
思路2:暴力法肯定也不是好的路子,那么二分法就该上场了。现在是一个无序的数组,如何二分呢?又该对谁二分呢?显然不可能是输入数组,那么只可能是输入数组中出现的1~n的数字(这数字不也可以看成时有序的么?)我们把数字1~n分为1~(n-1)/2和(n-1)/2+1~n,对分区间,遍历整个输入数组,统计前面那个区间的在输入数组中出现的次数,如果大于该区间的数字个数,那么重复数字必然出现在这个区间,否则就在另外一个区间。总的时间复杂度为O(nlogn),空间复杂度为O(1)。
依照这个思路,那么我们就可以写下如下代码:
package com.cb.java.algorithms.jianzhioffer;
public class DuplicateWithNoChangeInArray {
/**
* 利用二分法来解决
*
* @param args
*/
public static int findDuplicateNum2(int[] numbers) {
int length = numbers.length;
if (numbers == null || length <= 0)
return -1;
for (int i : numbers) {
if (i <= 0 || i >= length)
return -1;
}
int start = 1;
int end = length - 1;
while (start <= end) {
int middle = (end - start) / 2 + start;
int count = count(numbers, start, middle); // 统计开始点到中间点的
if (end == start) {
if (count > 1)
return start;
else
break;
}
if (count > (middle - start + 1))
end = middle;
else
start = middle + 1;
}
return -1;
}
private static int count(int[] numbers, int start, int end) {
int count = 0;
for (int num : numbers) {
if (num >= start && num <= end) {
++count;
}
}
return count;
}
public static void main(String[] args) {
int[] numbers = { 3, 6, 5, 4, 3, 2, 6, 4 };
// int dup = findDuplicateNum(numbers);
int dup = findDuplicateNum2(numbers);
System.out.println(dup);
}
}