question about missing element in array

后端 未结 2 1097
庸人自扰
庸人自扰 2020-12-30 18:17

i have following problem from book introduction algorithm second edition by MIT university

problem is following

An array A[1 . . n] contai

2条回答
  •  Happy的楠姐
    2020-12-30 18:49

    Call your missing number M.

    You can split your array into two parts depending on whether the least significant bit of A[i] is a 1 or a 0. The smaller of the two parts (call it P_1) is at most (n-1)/2 elements in size, and it tells you whether M's least significant bit is a 1 or a 0.

    Now consider the 2nd bit for the elements of P_1. Again, this part can be split in two, and the smaller of the two parts (P_2) tells you whether this bit should be a 1 or a 0.

    Carry on going (P_3, P_4, ...) until you've worked out what all the bits are.

    You can prove that this is O(n) because you are essentially looking at n + n/2 + n/4 + ... different individual bits in your array, and this sum is less than 2n.

提交回复
热议问题