找出数组中缺失的数

来源:互联网 发布:合味道口味 知乎 编辑:程序博客网 时间:2024/04/28 10:45

从数组0到n之间的整数拿掉一个,其余的数为数组A[1...n]的元素。由于A的元素以bit表示,所以不能一次获得A的整个元素。唯一能做的是取得A[i]的第j个bit。


An array A[1...n] contains all the integers from 0 to n except for one number

which is missing. In this problem, we cannot access an entire integer in A with
a single operation. The elements of A are represented in binary, and the only
operation we can use to access them is “fetch the jth bit of A[i]”, which takes
constant time. Write code to find the missing integer. Can you do it in O(n)

time? 


这个问题最大的约束是所求的数值必须依靠bit查询来决定。

假设n比2的k次幂小1,n = 2^k - 1。如果n不止比2^k小一,可以使用n+1,n+2...来填充。

假设2bit的数字00,01,10,11。如果将第一位的所有bit相加为偶数,第二位也是。从0到2^k - 1不管数有多少bit,只要把所有数的某一列bit相加,一定为偶数。

所以一个数字如果丢失时,某一列bit相加和如果为偶数,表示此数在这一列bit位为0。否则为1。

用数组b[k]存储丢失的数的每一位。b[0]表示第0位。

伪代码:

for j = 0 to k-1   b[j] = 0for i = 1 to n   for j = 0 to k-1      b[j] = (b[j] + fetch(a, i, j)) % 2


SOLUTION

Your first response to this question should be to ask about the O(N) requirement. The main
constraint of the problem is that the mystery number must be determined with only bit
inquiries.
Let’s assume that n is one less than a power of two (eg, n = 2^k - 1). If it’s not, it can be padded
with no more than n/2 values to make it so.
Consider the four two-bit numbers 00, 01, 10, 11. If you add up the one’s bit, you get an even
number. Likewise, if you add up two’s bit, you get an even number. No matter how many bits
in the number, if you add up a column, you get an even number.
Now if a number is missing, one of two things can happen to the column sums. Either it
remains the same, indicating the missing value didn’t contribute anything to the sum, or the
sum is different because the missing value did contribute. Normally, the sums are even. So if
they are different, they must be odd. If we keep a single bit count for each column, the result
will be the missing number.
for j = 0 to k-1   b[j] = 0for i = 1 to n   for j = 0 to k-1      b[j] = (b[j] + fetch(a, i, j)) % 2


Note that the modulus operator will impact implementation performance. You
should recommend that the it be replaced with a bit-wise and with 1.
原创粉丝点击