Q: 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?
A:
思路1:通过fetch将A[i]的每一位都可以取出,那么就很容易得到A[i]的值,有了值之后将数组求和,其与n*(n+1)/2 的差值就是丢失的数字。
思路2:思路1的方法很直观,但是效率还不够高。
以n = 13为例:
00000 00100 01000 01100
00001 00101 01001 01101
00010 00110 01010
--------- 00111 01011
可以发现其最低有效位LSB1 有则一定的规律
if n%2 == 1 then count(0s) = count(1s)
if n%2 == 0 then count(0s) = 1 + count(1s)
得到这样一个表格:
count(0s) = 1 + count(1s) | count(0s) = count(1s) | |
LSB(v) == 0 | 所以少了一个0,则count(0s) = counti(1s) | 所以少了一个0,则count(0s) < ounti(1s) |
LSB(v) == 1 | 所以少了一个1,则count(0s) > counti(1s) | 所以少了一个0,则count(0s) > counti(1s) |
if LSB(v) == 0, then 去除LSB为1的数据,对余下的数据对下一位的bit位进行判断
if LSB(v) == 1, then 去除LSB为0的数据,对余下的数据对下一位的bit位进行判断.
还是以例子说明,其最后一位count(0s) > count(1s), 由表格知道LSB(v)为1,则去除LSB为0的数据,即如下:
00000 00100 01000 01100
00001 00101 01001 01101
00010 00110 01010
--------- 00111 01011
对余下的数据统计其倒数第二位count(0s)和count(1s), 比较其大小,得到丢失数v的倒数第二位,并进一步删除数据。这样递归下去。
#include <iostream>
#include <vector>
using namespace std;
int fetch(int n, int i) {
return (n>>i)&1;
}
int getNum(int n) {
int ret = 0;
for (int i = 31; i >= 0; i--) {
ret = (ret<<1)|fetch(n,i);
}
return ret;
}
int findMissing1(int n, int a[]) {
int sum = 0;
int len = 8*sizeof(int);
for (int i = n-1; i >= 0; i--) {
sum += getNum(a[i]);
}
for (int i = 1; i <= n; i++) {
sum -= i;
}
return -sum;
}
int findMissing2(vector<int> &array, int ind) {
if (ind >= 32) {
return 0;
}
vector<int> zeroBits;
vector<int> oneBits;
for (int i = 0; i < array.size(); i++) {
if (fetch(array[i], ind)==1) {
oneBits.push_back(array[i]);
} else {
zeroBits.push_back(array[i]);
}
}
if (zeroBits.size() <= oneBits.size()) {
int v = findMissing(zeroBits, ind+1);
return (v<<1) | 0;
} else {
int v = findMissing(oneBits, ind+1);
return (v<<1) | 1;
}
}
int main() {
int a[6] = {0, 4, 5, 6, 1, 2};
vector<int> b;
for (int i = 0; i < 6; i++) {
b.push_back(a[i]);
}
cout<<findMissing1(6, a)<<endl;
cout<<findMissing2(b, 0)<<endl;
return 0;
}