Cracking the coding interview--Q5.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 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...n]包含所有从0到n的整数,除了丢失一个整数外。在这个问题中,我们不能通过用A[i]获取到第i个数,这个数组A表示成二进制数,我们唯一能使用的操作只有“取得A[i]中的第j位”, 这个操作只需要花费常数时间。写程序找出丢失的整数,你能使程序的时间复杂度是O(n)吗?

解答

取得A[i]中的第j位,对应函数fetch(A,i,j),所以,取整数i,只需要调用fetch函数32次即可。同时建立一个boolean数组,如果包含某个整数i,则将boolean数组的第i个元素设为true,在遍历一遍,就找到了那个整数不存在于其中……

	public static int fetch(int a[],int i,int j){
		return (a[i]>>j)&1;
	}
	public static int get(int[] a ,int i){
		int result = 0 ;
		for(int j=31;j>=0;--j){
			result = result<<1|fetch(a,i,j);
		}
		return result ;
	}

---EOF---

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值