44// ==================================================================
55
66// 面试题3(二):不修改数组找出重复的数字
7- // 题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,
8- // 但不能修改输入的数组。例如,如果输入长度为7的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的输出是重复的数字2或者3。
7+ // 题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至
8+ // 少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的
9+ // 数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的
10+ // 输出是重复的数字2或者3。
911
1012#include < iostream>
1113
12- int countRange (int * numbers, int length, int start, int end);
14+ int countRange (const int * numbers, int length, int start, int end);
1315
1416// 参数:
1517// numbers: 一个整数数组
1618// length: 数组的长度
1719// 返回值:
1820// 正数 - 输入有效,并且数组中存在重复的数字,返回值为重复的数字
1921// 负数 - 输入无效,或者数组中没有重复的数字
20- int getDuplication (int * numbers, int length)
22+ int getDuplication (const int * numbers, int length)
2123{
2224 if (numbers == nullptr || length <= 0 )
2325 return -1 ;
2426
2527 int start = 1 ;
26- int end = length;
28+ int end = length - 1 ;
2729 while (end >= start)
2830 {
2931 int middle = ((end - start) >> 1 ) + start;
@@ -44,7 +46,7 @@ int getDuplication(int* numbers, int length)
4446 return -1 ;
4547}
4648
47- int countRange (int * numbers, int length, int start, int end)
49+ int countRange (const int * numbers, int length, int start, int end)
4850{
4951 if (numbers == nullptr )
5052 return 0 ;
0 commit comments