careercup5.7

/*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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值