面试题3:不修改数组找出重复的数字
题目:在一个长度为n+1的数组里的所有数字都在1到n的范围内,所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2, 3, 5, 4, 3, 2, 6, 7},那么对应的输出是重复的数字2或者3。
#include<cstdio>
#include<iostream>
// ====================找重复数字====================
int countrage(int* number, int length, int start, int middle){
if (number == nullptr || length < 0)
return 0;
int count = 0;
for (int i = 0; i < length; i++){
if (number[i] >= start && number[i] <= middle)
++count;
}
}
int getDuplication(int* numbers, int Length){
if (numbers == nullptr || Length == 0)
{
return -1;
}
int start = 1;
int end = Length - 1;
while (start <= end)
{
int middle = ((end - start) >> 1) + start;
int count = countrage(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;
}
// ====================测试====================
void test(const char* testname, int* numbers, int Length, int* duplications, int dupLength){
int result = getDuplication(numbers, Length);
for (int i = 0; i < dupLength; ++i)
{
if (result == duplications[i])
{
std::cout << testname << " passed." << std::endl;
return;
}
}
std::cout << testname << " FAILED." << std::endl;
}
void test1(){
int a,b;
int numbers[] = { 2, 3, 5, 4, 3, 2, 6, 7 };
int duplications[] = {2, 3};
test("test1", numbers, sizeof(numbers)/sizeof(int), duplications, sizeof(duplications)/sizeof(int));
}
void main(){
test1();
}