3dmax寻找丢失贴图
Problem statement
问题陈述
We are given a list of n-1 integers and the integers range from 1 to n. There are no duplicates in the list. Only one of the integer from 1 to n is missing. We need to find the missing number in O(n) time complexity.
我们给出了n-1个整数的列表,这些整数的范围是1到n。 列表中没有重复项。 从1到n的整数中只有一个丢失。 我们需要找到O(n)时间复杂度中的缺失数 。
Solution
解
The simplest solution is to take each number from 1 to n and to check whether it exists in the array or not. But such approach has O(n2) time complexity. Thus we need to find some advance algorithm to reduce the time complexity.
最简单的解决方案是将每个数字从1取到n,并检查它是否存在于数组中。 但是这种方法具有O(n 2 )时间复杂度 。 因此,我们需要找到一些先进的算法来减少时间复杂度。
The algorithm is illustrated below:
该算法如下图所示:
XOR all the elements presented in the array. Let the result be x.
对数组中显示的所有元素进行XOR 。 令结果为x 。
XOR all numbers from 1 to n. Let the result be y.
将所有数字从1到n进行 XOR 。 令结果为y 。
XORing x & y gives the missing number.
对 x和y 进行XORing运算得出缺失的数字。
C code for implementation
实现的C代码
#include<stdio.h>
#include<stdlib.h>
int missingNo(int* a, int n){
int x=0,y=0;
for(int i=0;i<n-1;i++){
//xoring all elements
x^=a[i];
}
for(int i=1;i<=n;i++){
//xoring 1 to n
y^=i;
}
//xoring x & y outputs missing number
return x^y;
}
int main()
{
int n,x,count=0;
printf("enter your range\n");
scanf("%d",&n);
printf("enter elements leaving one nummber in the range 1 to n\n");
// dynamic array created for n-1 elements
int* a=(int*)(malloc(sizeof(int)*(n-1)));
for(int i=0;i<n-1;i++){
scanf("%d",&a[i]);
}
// function to check duplicate exists or not
printf("\nthe missing number is %d\n",missingNo(a,n));
return 0;
}
Output
输出量
enter your range
5
enter elements leaving one nummber in the range 1 to n
2
4
3
5
the missing number is 1
Time complexity: O(n) (for scanning the array)
时间复杂度: O(n)(用于扫描阵列)
Space complexity: O(1)
空间复杂度: O(1)
翻译自: https://www.includehelp.com/algorithms/finding-the-missing-number.aspx
3dmax寻找丢失贴图