Algorithm 判断两组数是否不相交的有效算法

Algorithm 判断两组数是否不相交的有效算法,algorithm,disjoint-sets,Algorithm,Disjoint Sets,为软件开发人员面试而练习,并在一个算法问题上陷入困境 Given two sets of unsorted integers with array of length m and other of length n and where m < n find an efficient algorithm to determine if the sets are disjoint. I've found solutions in O(nm) time, but haven't found

为软件开发人员面试而练习,并在一个算法问题上陷入困境

Given two sets of unsorted integers with array of length m and other of 
length n and where m < n find an efficient algorithm to determine if 
the sets are disjoint. I've found solutions in O(nm) time, but haven't 
found any that are more efficient than this, such as in O(n log m) time.
给定两组未排序的整数,数组长度为m,另一组长度为
长度n和其中m
相当明显的方法-对长度为
m
-
O(m log m)
的数组进行排序。
对于长度
n
数组中的每个元素,使用二进制搜索检查它是否存在于长度
m
-
O(log m)
每个元素=
O(n log m)
。由于
m使用具有O(1)查找/插入的数据结构,您可以轻松插入第一个集合的所有元素

然后,对于第二个集合中的每个元素,如果它不存在不相交,则它是不相交的

伪码

function isDisjoint(list1, list2)
    HashMap = new HashMap();
    foreach( x in list1)
        HashMap.put(x, true);

    foreach(y in list2)
        if(HashMap.hasKey(y))
             return false;
    return true;

这将为您提供一个O(n+m)解决方案

这里有一个链接,指向一篇我认为可以回答您问题的帖子

Given two sets of unsorted integers with array of length m and other of 
length n and where m < n find an efficient algorithm to determine if 
the sets are disjoint. I've found solutions in O(nm) time, but haven't 
found any that are more efficient than this, such as in O(n log m) time.
3) 排序较小的对象((m+n)logm)

  • 比如说,m
  • 将B的每个元素二进制搜索为A

  • 缺点:修改输入

    看起来像是切鲁维安打败了我,但你可以使用哈希表在平均情况下得到
    O(n+m)

    *将
    m
    的所有元素插入表中,假设没有很多元素使用相同的散列,则每个元素(可能)占用固定的时间。此步骤是
    O(m)

    *对于
    n
    的每个元素,检查是否在表中。如果是,则返回false。否则,请继续下一步。这需要
    O(n)

    *如果表中没有,则返回true


    正如我之前所说的,这是因为哈希表在平均情况下提供恒定的查找时间。在极少数情况下,
    m
    中的许多唯一元素具有相同的散列,这将花费稍长的时间。然而,大多数人不需要关心假设的最坏情况。例如,快速排序比合并排序更常用,因为它提供了更好的平均性能,尽管有
    O(n^2)
    上限。

    O(n log m)不是比O(n)慢吗?McLovin比我快。。O(n)