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

后端 未结 4 1772
天涯浪人
天涯浪人 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 12:46

    If we have repeated pair of numbers, they would not add anything to xor results, as the xor of them would be zero. Only pair of different number would add non zero bits to xor result.

    a xor a = 0
    [a, b, c, b, d, a]
    a xor b xor c xor b xor d xor a = c xor d
    

    Now in c xor d, the only set bits are the bits that are different in c and d. Let's say 3rd bit is set in c xor d. This means if bit 3 is 0 in c it would be 1 in d or vice versa.

    So if we divide all numbers in 2 group, one which contains all numbers with bit 3 is 0, and other in which bit 3 is 1, c and d would definitely go to different groups. And all pairs of same numbers would go the same group. (Bit 3 is either 1 on both a or 0 in both a)

    Let's say the groups are

    [a c a] and [b d b]
    xoring them
    a xor c xor a = c (The first number)
    b xor d xor b = d (The second number)
    

    Other possibilities of groups are

    [c] and [a b d b a]
    xoring them
    c = c (The first number)
    a xor b xor d xor b xor a = d (The second number)
    

    and

    [a b c b a] and [d]
    xoring them
    a xor b xor c xor b xor a= c (The first number)
    d = d (The second number)
    

    About

    set_bit_no = xor & ~(xor-1);
    

    If input array was composed of natural numbers, xor would be positive xor & ~xor is zero (Definition as all bits are inverted) On subtracting 1 from xor,

    1. If right most bit was zero it would be set to 1 and exit
    2. Reset rightmost bit to zero and try to add 1 to next bit (step 1)

    In short all rightmost bits that were 1 would become zero(inverted back similar to xor) and first (rightmost) zero bit would become 1(same as xor). Now on anding, all bits left of this newly set 1 bit are different in xor and ~(xor-1), so they would generate 0, all bits right to this newly set 1 bit are zero in both xor and ~(xor-1) so they would generate 0. Only bit at bit position where 1 was newly set in ~(xor-1) is 1 in both case, so only this bit would be set in expression xor & ~(xor-1)

提交回复
热议问题