【发布时间】:2013-08-22 12:51:42
【问题描述】:
我得到了一个包含 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 的 XOR 是如何在上述情况下找到丢失的整数的?
【问题讨论】:
-
暴力破解怎么样?对数组进行排序,检查
[n - (n-1)]不等于1 的几个索引。 -
为什么有最大允许整数?
-
@VoronoiPotato:如果序列中有 10 亿个数字并且他被限制为 32 位整数怎么办?
-
@Renan 因为那更慢?无论如何,OP 并没有要求替代解决方案,而是要求提出的解决方案为何/如何工作。