棘手的算法问题
可能的重复:
在数组中查找缺失数字的最快方法数字
输入:未排序数组 A[1,..,n],其中包含 0,..,n 范围内除一个整数之外的所有整数
问题是在 O(n) 时间内确定丢失的整数。 A 的每个元素是 以二进制表示,唯一可用的操作是函数 bit(i, j),其中 返回 A[i] 第 j 位的值,花费常数时间。
有什么想法吗?我认为某种分而治之的算法是合适的,但我想不出我到底应该做什么。提前致谢!
Possible Duplicate:
Quickest way to find missing number in an array of numbers
Input: unsorted array A[1,..,n] which contains all but one of the integers in the range 0,..,n
The problem is to determine the missing integer in O(n) time. Each element of A is
represented in binary, and the only operation available is the function bit(i, j), which
returns the value of the jth bit of A[i] and takes constant time.
Any ideas? I think some sort of divide-and-conquer algorithm would be proper, but I can't think of what exactly I should do. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个数学属性,即
1
和n
之间的数字之和,其中n
为n(n+1)/2< /代码>。您可以看到
10
的情况:因此,通过扩展,它是从
0
到n
的数字之和,因为您只是添加 0到它。因此,您要做的就是将所有数字相加并进行计数,然后使用该公式算出缺少的数字。因此,类似这样的事情:
使用
bit(i,j)
获取数字是很棘手的,因此您必须单独提取各个位并将它们转换为实际数字以进行求和。It's a mathematical property that the sum of the numbers between
1
andn
wheren
isn(n+1)/2
. You can see this for10
:So, by extension, is the sum of the numbers from
0
thrun
since you're just adding 0 to it. So what you do is add up all the numbers and maintain a count, then use that formula to figure out the missing one.So, something like:
Getting the number with
bit(i,j)
is tricky so you'll have to extract the bits individually and turn them into actual numbers for summing.您可以使用 XOR 运算符,因为它比加法更快。由于您可以访问每个位,因此您将在此处进行按位异或。
这里使用的原理是 (A XOR B XOR A ) = B
例如: (1 XOR 2 XOR 3) XOR (1 XOR 2) = 3
You could use XOR operator as its faster than addition. Since you have access to each bit you will be doing a bitwise XOR here.
The principle to be used here is (A XOR B XOR A ) = B
eg: (1 XOR 2 XOR 3) XOR (1 XOR 2) = 3
这是一个棘手的问题,因为使用位方法只需要循环每个数字的每一位,这意味着它会自动变成 O(n*j),其中 j 是代表 n 的位数。
我认为 paxdiablo 已经明白了,假设您被允许使用不使用位方法的解决方案。
It's a trick question then, since using the bit method would only require that you cycle each bit for each number, meaning it would automatically become O(n*j) where j is the number of bits representing n.
I think paxdiablo's got it, assuming you're allowed a solution which doesn't use the bit method.