P42,文字倒数第五行:“我们在统计数字3或者4在数组中出现的次数,它们一共出现了三次。”应该删除,因为这里并没有统计3或4的次数为三次,而是直接统计了3的次数,然后再统计了一次3的次数,得出3是重复的数字。
#include <iostream>
int countRange(const int* numbers, int length, int start, int end)
{
if (numbers == nullptr)
{
return 0;
}
int count = 0;
for (int i = 0; i < length; i++)
{
if (numbers[i] >= start && numbers[i] <= end)
++count;
}
return count;
}
int getDuplication(const int* numbers, int length)
{
if (numbers==nullptr || length <= 0)
{
return -1;
}
int start = 1;
int end = length - 1;
while (end >= start)
{
int middle = ((end - start) >> 1) + start;
int count = countRange(numbers,length,start,middle);
std::cout << "start=" << start << ",end=" << end << ",middle=" << middle << ",count=" << count << std::endl;
if (end == start)
{
if (count > 1)
return start;
else
break;
}
if (count > (middle - start + 1))
{
end = middle;
}
else
start = middle + 1;
}
return -1;
}
int main()
{
int a[] = {2,3,5,4,3,2,6,7};
int num = getDuplication(a, 8);
std::cout << "num=" << num << std::endl;
return 0;
}