题目:给定数组A,大小为n,数组元素为0到n-1的数字,不过有的数字出现了多次,有的数字没有出现。请给出算法和程序,统计哪些数字没有出现,哪些数字出现了多少次。要求在O(n)的时间复杂度,O(1)的空间复杂度下完成。
解法一:
直接用两层遍历,O(n^2)的时间复杂度,O(1)的空间复杂度
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, count = 0; //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++)
{
count = 0;
for (j = 0; j < n; j++)
{
if (i == a[j])
{
count++;
}
}
if (count == 0)
printf("%d does not appear in the array!\n", i);
else
printf("%d appear in t