我给出了一个n个整数的列表,这些整数的范围是1到n。列表中没有重复项,但列表中缺少其中一个整数。我必须找到缺失的整数。查找序列中缺少的数字
Example: If n=8
I/P [7,2,6,5,3,1,8]
O/P 4
I am using a simple concept to find the missing number which is to get the
sum of numbers
total = n*(n+1)/2
And then Subtract all the numbers from sum.
但是,如果数字的总和超出了最大允许的整数,上述方法将失败。
所以我搜索的第二溶液,我发现一种方法如下:
1) XOR all the elements present in arr[], let the result of XOR be R1.
2) XOR all numbers from 1 to n, let XOR be R2.
3) XOR of R1 and R2 gives the missing number.
这是如何工作的方法。如何是R1的异或和R2发现在上述情况下丢失的整数?
暴力强制它如何?对数组进行排序,检查'[n - (n-1)]'不等于1的索引对。 – Renan
为什么会有最大允许的整数? – VoronoiPotato
@VoronoiPotato:如果序列中有10亿个数字并且他仅限于32位整数,该怎么办? –