确定两组数字是否不相交的有效算法

时间:2014-07-08 19:41:40

标签: 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 any that are more efficient than this, such as in O(n log m) time.

4 个答案:

答案 0 :(得分:5)

使用具有O(1)查找/插入的数据结构,您可以轻松插入第一组的所有元素。

然后在第二组中的foreach元素,如果它不存在不相交,否则它是不相交的

伪代码

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)解决方案

答案 1 :(得分:4)

相当明显的方法 - 对长度为m - O(m log m)的数组进行排序。 对于长度为n的数组中的每个元素,请使用二进制搜索来检查它是否存在于长度为m的数组中 - 每个元素的O(log m) = O(n log m)。自m<n起,这加起来为O(n log m)

答案 2 :(得分:3)

看起来Cheruvian打败了我,但您可以使用哈希表在平均情况中获取O(n+m)
*将m的所有元素插入到表中,假设没有相同的哈希值,可能会为每个元素占用(可能)恒定的时间。这一步是O(m)
*对于n的每个元素,请检查它是否在表中。如果是,则返回false。否则,继续前进。这需要O(n) *如果表中没有,则返回true。

正如我之前所说的,这是有效的,因为哈希表在平均情况下给出了恒定的查找时间。在罕见的情况下,m中的许多独特元素具有相同的哈希值,因此需要稍长的时间。但是,大多数人不需要关心假设的最坏情况。例如,快速排序比合并排序更多,因为它提供了更好的平均性能,尽管有O(n^2)上限。

答案 3 :(得分:2)

这里是我认为可以回答您问题的帖子的链接。

3)排序较小的O((m + n)logm)

  1. 说,m&lt; n,排序A
  2. 二进制搜索B的每个元素到A
  3. 缺点:修改输入