标签:
题目:在一个长度为n的数组里所有数字都在0到n-1的范围里。数组中某些数字是重复的,但是不知道有几个数字重复了,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3.以数组a[7]={2,3,1,0,2,5,3}为例,分析如下图所示:
#include <iostream>
using namespace std;
int arr[7]={2,3,1,0,2,5,3};
void Swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
bool duplicate(int array[],int length,int *duplication)
{
if(array==NULL || length<0)
return false;
for(int i=0;i<length;i++)
{
if(array[i]<0 || array[i]>length-1 )
return false;
}
for(int i=0;i<length;++i)
{
while(array[i]!=i)
{
if(array[i]==array[array[i]])
{
*duplication=array[i];
return true;
}
Swap(array[i],array[array[i]]);
}
}
return false;
}
int main()
{
int result;
bool res;
res=duplicate(arr,7,&result);
if(res)
cout<<"重复的数是:"<<result<<endl;
else
cout<<"数据里没有重复的数!"<<endl;
system("pause");
return 0;
}
运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51775734