Distinguishing extra element from two arrays?

后端 未结 19 688
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 09:45

One of my friend was asked this question in an interview -

  • You have given two integer arrays each of size 10.
  • Both contains 9 equal elements (say 1 t
19条回答
  •  猫巷女王i
    2020-12-28 10:29

    This can be done using Xor.

    First Xor all elements from both arrays. Let x and y be the extra element each array. What remains is x^y.

    Now in xor, if a bit is set, it means that it is set in one of the the two numbers and not in the other one.

    We can use this to find the missing indivdual numbers. So find a bit which is set in a^b. Getting Righmost bit is easy. It can be done by

    n& ~(n-1)

    (1110) & ~(1101) = 0010

    To get each of the individual numbers, we split the numbers of both the arrays into 2 parts, numbers have the checked bit set, and which don't.We do XOR on each of the set, so that we get the values a and b. This cancels out all the repeating elements, and separates out x and y.

    This can be quite confusing. Now take x=3, y = 2

    x=110

    y=010

    x^y=100

    So when we get the bit set, the number we get is bitset = 100. Third bit is set. Suppose array elements be 5,1 ( Both repeated twice)

    5=101

    6=001

    What now, 5 has 3rd bit, so we xor it with x

    we get x^5^5 = x

    Similarly, 6 doesn't have 3rd bit set, so xor with y.

    We get y^1^1 = y

    Code

    for(i=0;i

    This is similar to the method posted here http://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/

提交回复
热议问题