且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从两个数组区别额外的元素?

更新时间:2022-12-09 19:05:40

如果您需要这个规模的话,我会用世界上很多集实现之一。例如,Java的HashSet的。

扔都在集中的第一个阵列。然后,对第二阵列中的每个成员,如果是包含在集移去;否则,将其标记为独特的#2。这个过程后,该组最后剩下的成员是唯一#1。

我可能会做这种方式,即使在接受记者采访时,甚至对于简单的十个元素的数组。人生苦短,来尝试找到巧妙的方法来扩展墙上时,有中有一个完美的门。

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 to 9)
  • Only one element is different.

How will you find the different element? What are different approaches you can take?

One simple but lengthy approach would be - sort both arrays,go on comparing each element,on false comparison, you'll get your result.

So what are different approaches for this? Specify logic as its expected in an interview. Not expecting a particular code in a specific language. Pseudo code will suffice.

(Please submit one approach per answer)

My purpose of asking this question is, its OK when array sizes are small.But when array size increases, you must think of a very efficient n faster way.Its never desirable to use comparisons in such case.

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.