1.法一:映射法
时间复杂度:O(N)
空间复杂度:O(N)
#include<stdio.h>
#include<stdlib.h>
#define N 5
int num(int* a, int n)
{
int* p = (int*)malloc(sizeof(int)*(n+1));
for (int i = 0; i < n + 1; i++)
{
*(p+i) = -1;
}
for (int i = 0; i < n; i++)
{
*(p + *(a + i)) = *(a + i);
}
for (int i = 0; i < n + 1; i++)
{
if ((*(p+i)) == -1)
return i;
}
}
int main()
{
int a[N] = { 0 };
for (int i = 0; i < N; i++)
{
scanf("%d", a + i);
}
printf("%d", num(a, N));
return 0;
}
2.法二:异或法
时间复杂度:O(N)
#include<stdio.h>
#include<stdlib.h>
#define N 5
int num(int* a, int n)
{
int x = 0;
for (int i = 0; i <= n; i++)
{
x ^= i;
}
for (int i = 0; i < n; i++)
{
x ^= a[i];
}
return x;
}
int main()
{
int a[N] = { 0 };
for (int i = 0; i < N; i++)
{
scanf("%d", a + i);
}
printf("%d", num(a, N));
return 0;
}
3.法三:差值法
时间复杂度:O(N)文章来源:https://www.toymoban.com/news/detail-515048.html
#include<stdio.h>
#include<stdlib.h>
#define N 5
int num(int* a, int n)
{
int s = (n * (n + 1)) / 2;
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += a[i];
}
return s - sum;
}
int main()
{
int a[N] = { 0 };
for (int i = 0; i < N; i++)
{
scanf("%d", a + i);
}
printf("%d", num(a, N));
return 0;
}
4.法四:排序+查找
时间复杂度:O((N+1)*logN)文章来源地址https://www.toymoban.com/news/detail-515048.html
到了这里,关于C语言--消失的数字的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!