您的位置:首页 > 职场人生

面试题三:数组中重复的数字

2018-01-31 21:43 295 查看
题目一:

在一个长度为n的数组里的所有数字都在0~n-1的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3.

#include<iostream>
using namespace std;
bool duplicate(int *a,int n){
int t;
for(int i=0;i<n;i++){
while(a[i]!=i){
if(a[i]==a[a[i]])
{
return true;
}
t=a[i];
a[i]=a[t];
a[t]=t;
}
}
return false;
}
int main(void){
int a[7]={2,3,1,0,2,5,3};
bool flag=duplicate(a,7);
if(flag==true)
cout<<"True"<<endl;
else
cout<<"False"<<endl;
for(int i=0;i<8;i++){
cout<<a[i]<<"\t";
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: