从1到N-1有一个值重复两次,找出重复值。
如4,3,5,8,5,2,1,9,6,7中找出重复值为5。
1.用两个数组,不要求时间复杂度
略。
2.用两个数组,时间复杂度为O(n)。
#include <stdio.h>
int main()
{
int a[10]={4,2,6,9,5,3,1,3,7,8};
int count[10]={0};
int i,t;
int swap=0;
for(i=0;i<10;i++)
{
t=a[i];
if(count[t-1]==1)
{
printf("%d\n",t);
break;
}
count[t-1]=1;
}
return 0;
}
3.用一个数组和一个变量,时间复杂度为O(n)。
#include <stdio.h>
int main()
{
int a[10]={4,3,6,9,5,8,1,2,3,7}; //1—N-1的N个数
int temp=10,i;
int swap=0;
for(i=0;i<10;i++)
{
if(a[temp-1]!=temp) //判断a[temp-1]是否等于temp,
//不等则交换temp和a[temp-1]的值
//相等则说明temp和a[temp-1]两个数重复
{
swap=a[temp-1];
a[temp-1]=temp;
temp=swap;
}
else
{
printf("%d\n",temp);
break;
}
}
return 0;
}