题目:给定数组A,大小为n,数组元素为0到n-1的数字,不过有的数字出现了多次,有的数字没有出现。请给出算法和程序,统计哪些数字没有出现,哪些数字出现了多少次。要求在O(n)的时间复杂度,O(1)的空间复杂度下完成。
两次遍历数组的方法:考虑A[i],现在的位置为i,如果采用A来计数,它的位置应该是A[i]%n,找到计数位置,处理这个计数位置的办法就是加n.
第一次遍历:对A[i]的计算位置加n,加n可以保证A[i]%n的是不变的
第二次遍历:A数组,最后每一个元素表示为A[i] = x + k * n; 其中x<n,并且k就是我们要统计的频率
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i; //n is The length of the Array
while (scanf("%d", &n) != EOF)
{
int *a = malloc(sizeof(int) * n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
a[a[i] % n] += n;
for (i = 0; i < n; i++)
{
if (a[i] / n == 0)
printf("%d does not appear in the array!\n", i);
else
printf("%d appear in the array for %d times\n", i, a[i]/n);
}
}
}