文章目录
- 1.法一:映射法
- 2.法二:异或法
- 3.法三:差值法
- 4.法四:排序+查找
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)
#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)