一个大小为n的数组,里面的数都属于范围[0, n-1],有不确定的重复元素,找到至少一个重复元素,要求O(1)空间和O(n)时间。
#include <stdio.h>
const int NO_REPEAT_FLAG = -1;
int FindRepeatNumberInArray(int *a, int n)
{
for(int i = 0; i < n; i++)
{
int nRealIndex = a[i] >= n ? a[i] - n : a[i];
if (a[nRealIndex] >= n) //这个位置上的值大于n说明已经是第二次访问这个位置了
return nRealIndex;
else
a[nRealIndex] += n;
}
return NO_REPEAT_FLAG; //数组中没有重复的数
}
void PrintfArray(int a[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
putchar('\n');
}
int main()
{
const int MAXN = 10;
//int a[MAXN] = {2, 4, 1, 5, 7, 6, 1, 9, 0, 2};
int a[MAXN] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 0};
printf("数组为: \n");
PrintfArray(a, MAXN);
int nRepeatNumber = FindRepeatNumberInArray(a, MAXN);
if (nRepeatNumber != NO_REPEAT_FLAG)
printf("该数组有重复元素,此元素为%d\n", nRepeatNumber);
else
printf("该数组没有重复元素\n");
return 0;
}