/*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 opera-
tion 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?
*/
#include <iostream>
#include <bitset>
using namespace std;
int findd(bitset<5> ar[], int col,int n){
bitset<5> odd[11];
bitset<5> even[11];
int o=0,e=0;
for(int i=0;i<n;i++)
if(ar[i][col])
odd[++o] = ar[i];
else even[++e] = ar[i];
if(o>e)
return (findd(even, col +1,e)) << 1 | 0;
else if(o<e) return (findd(odd, col +1,o)) << 1 | 1;
else return 0;
}
int main(){
bitset<5> ar[11];
int x[11]={0,1,2,3,4,5,7,8,9,10,11};
for(int i = 0; i<11; i++){
bitset<5> temp(x[i]);
ar[i] = temp;
}
cout<<findd(ar,0,11)<<endl;
}
算法导论上也有这一题。原理就是一位一位看,0多就缺1,1多就缺0.如果一样多,应该是到顶了,前面都是0了,每次走的时候把多的那部分去掉,多0就取所有位数为0的。 这样一来,O(x)<=O(n)+O(n/2)+O(n/4)=O(2n)=O(n)