算法说,如果两个数组有相同的成员 [英] Algorithm to tell if two arrays have identical members

查看:173
本文介绍了算法说,如果两个数组有相同的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的算法比较两个数组,看看他们是否有相同的成员?

假定没有重复,各成员可以在任何顺序,并且,无论是排序。

 比较(
    [A B C D],
    [B,A,D,C]
)==>真正

比较(
    [A,B,E],
    [A,B,C]
)==>假

比较(
    [A,B,C],
    [A,B]
)==>假
 

解决方案

明显的答案是:

  1. 排序两个列表,然后检查每个 元素,看它们是否相同
  2. 从一个阵列添加项目到 哈希表,然后通过迭代 其他数组,检查每个项目 在散列
  3. 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:

  1. Sort both lists, then check each element to see if they're identical
  2. Add the items from one array to a hashtable, then iterate through the other array, checking that each item is in the hash
  3. 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.

这篇关于算法说,如果两个数组有相同的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆