Explain using xor to find two non-duplicate integers in an array

后端 未结 4 1776
天涯浪人
天涯浪人 2020-12-23 12:23

Given [1,1,4,5,5,6] we can find 4 and 6 to be the non-repeating integers.

There is a solution using XOR.

4条回答
  •  爱一瞬间的悲伤
    2020-12-23 13:00

    This algorithm would only work if and only if

    1) elements are non-zero
    2) contains no more than 2 non-repeating integers. If only 1
       non-repeating, one of the result (x or y) will be 0.
    3) the repeated numbers occurs in pairs (ie. 2,4,6....)
    

    If 0 is a possible number, then you can't differentiate between an answer found or no answer.

    By XORing all the elements, this gives the difference between the 2 non-repeating integers (ie. 4 ^ 6 in your example). This is because all the other elements would be repeating (ie. even amount of times) and in XOR, they cancel themselves out. It is important to note that XOR is commutative (ie. order doesn't matter a^b = b^a)

    Now the set_bit_no. This just stores the right most set bit or xor. Why the right most? Because it is easy to get I guess. But any set bit would do. The set bits in xor variable contains the bits where it is different between 4 and 6.

    100 ^ 110 = 010
    

    The second bit is 1 because that's the only bit different between 4 and 6. Similarly the difference between 3 and 8

    0011 ^ 1000 = 1011
    

    which shows 4th, 2nd and 1st bit are different between 3 and 8.

    The reason to get the set bit and use that in the if condition is to make sure the answers (4 and 6) is written to different variable (x or y). Why does this work? Because the set bit guarantees that the 2 answers will contain different values at that bit position.

    if(arr[i] & set_bit_no)
    

提交回复
热议问题