Distinguishing extra element from two arrays?

后端 未结 19 590
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 10:29

    If you need this to scale, then I would use one of the many Set implementations in the world. For example, Java's HashSet.

    Throw all of the first array in the Set. Then, for each member of the second array, if it is contained in the Set, remove it; otherwise mark it as Unique #2. After this procedure, the last remaining member of the Set is Unique #1.

    I'd probably do it this way, even on an interview, and even for simple ten-element arrays. Life is too short to spend trying to find the clever way to scale a wall when there's a perfectly good door in it.

提交回复
热议问题