题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的输出是重复的数字2或者3。
输入长度为n的数组,函数countRange将被调用O(logn)次,每次需要O(n)的时间,总的复杂度为O(nlogn)
空间复杂度为O(1)
#include<cstdio>
#include<iostream>
using namespace std;
// 统计 1~n 出现次数
int countRange(const int* numbers, int length, int start, int end);
int getDuplication(const int* numbers, int length);
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; //右移一位相当于/2;左移相当于*2
int count = countRange(numbers, length, 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;
}
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 main()
{
int numbers[] = { 2, 3, 5, 4, 3, 2, 6, 7 };
int len = 8;
int test[] = { 2, 3, 4 };
int result = getDuplication(numbers, len);
for (int i = 0; i < 4; ++i)
{
if (result == test[i])
{
cout << "P~" << endl;
}
else
cout << "F~" << endl;
}
return 0;
}