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

2023-09-11 02:02:57 作者:终于有人爱我了

我的一位朋友被要求在接受记者采访这个问题 -

您已经给两个整型数组各尺寸的10 在这两个包含9个相等的元素(比如1〜9) 只有一个元素是不同的。

你怎么会找到不同的元素?有哪些不同的方法可以采取?

  

一个简单而冗长的方法是 - 两个数组排序,去比较各个元素,假的比较,你会得到你的结果。

那么,什么是不同的方法呢?指定为预期在接受采访时的逻辑。没想到一个特定的code在特定的语言。伪code就足够了。

(请提供每回答一个方法)

  

我问这个问题的目的是什么,它​​的确定,当数组大小small.But当数组大小增加时,你必须考虑的一个非常有效ñ更快way.Its永远需要使用比较在这种情况下。

解决方案

如果您需要这个规模的话,我会用世界上很多集实现之一。例如,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. OJ题 移除元素 合并两个有序数组

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.

 
精彩推荐