Distinguishing extra element from two arrays?

后端 未结 19 687
爱一瞬间的悲伤
爱一瞬间的悲伤 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:41

    This can be solved quickly from just the sum and the sum of the squares of the two sequences. And calculating these sums will certainly be faster than the hashes that are suggested, and doesn't involve any comparisons between the sequence items.

    Here's how to do it: If the two sets are {ai} and {bi}, then call A and B their sums, and A2 and B2 are the sum of the squares, i.e. A2 = Sum({ai2}), and for convenience, D=A-B, and D2=A2-B2. Therefore, D=a-b and D2=a2-b2, where a and b are the two elements that are different, and from this we see

    a = (D2+D2)/(2*D)
    b = a - D

    This works out because, from algebra, a2-b2=(a+b)(a-b) or D2=(a+b)D, so a+b=D2/D, and since we also know a-b, we can find a and b.

    An example in Python may be more convincing

    a, b = 5, 22   # the initial unmatched terms
    x, y = range(15), range(15)
    y[a] = b
    print "x =", x  # x = [0, 1, 2, 3, 4,  5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    print "y =", y  # y = [0, 1, 2, 3, 4, 22, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    
    D = sum(x) - sum(y)
    D2 = sum([i**2 for i in x]) - sum([i**2 for i in y])  #element-wise squaring
    a = (D2+D*D)/(2*D)
    b = a - D
    
    print "a=%i, b=%i" % (a, b)
    #prints a=5, b=22  which is correct
    

    (Of course, this is somewhat similar to jk's answer, except it doesn't require the multiplication of all the terms and the huge numbers that would result, but thanks to jk for the idea of a mathematical approach.)

提交回复
热议问题