本文介绍了算法说,如果两个数组有相同的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是最好的算法比较两个数组,看看他们是否有相同的成员?
假定没有重复,各成员可以在任何顺序,并且,无论是排序。
比较(
[A B C D],
[B,A,D,C]
)==>真正
比较(
[A,B,E],
[A,B,C]
)==>假
比较(
[A,B,C],
[A,B]
)==>假
解决方案
明显的答案是:
- 排序两个列表,然后检查每个元素,看它们是否相同
- 从一个阵列添加项目到哈希表,然后通过迭代其他数组,检查每个项目在散列
- nickf的迭代搜索算法
哪一个你会使用将取决于是否可以在列表第一排序,你是否有一个好的哈希算法派上用场了。
What's the best algorithm for comparing two arrays to see if they have the same members?
Assume there are no duplicates, the members can be in any order, and that neither is sorted.
compare(
[a, b, c, d],
[b, a, d, c]
) ==> true
compare(
[a, b, e],
[a, b, c]
) ==> false
compare(
[a, b, c],
[a, b]
) ==> false
解决方案
Obvious answers would be:
- Sort both lists, then check eachelement to see if they're identical
- Add the items from one array to ahashtable, then iterate through theother array, checking that each itemis in the hash
- nickf's iterative search algorithm
Which one you'd use would depend on whether you can sort the lists first, and whether you have a good hash algorithm handy.
这篇关于算法说,如果两个数组有相同的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!