剑指offer读书笔记之不修改数组找出数组中重复的数字

在一个长度为n+1的数组里的数字都在1~n的范围内,所以数组内至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class {
public static void main(String[] args) {
int[] arr = {2, 3, 5, 4, 3, 2, 6, 7};
System.out.println(findDuplicate(arr));
}
private static int findDuplicate(int[] arr) {
if (arr == null || arr.length == 0) {
return -1;
}
int start = 1;
int end = arr.length - 1;
while (end >= start) {
int middle = ((end - start) >> 1) + start;
int count = countRange(arr, 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 countRange(int[] arr, int start, int end) {
if (arr == null || arr.length == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= start && arr[i] <= end) {
++count;
}
}
return count;
}
}