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

标签 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.

最佳答案

使用具有 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) 的解决方案

关于algorithm - 确定两组数字是否不相交的有效算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24640429/

相关文章:

arrays - 在 NxNxN 二进制数组中找到仅包含 1 的最大长方体

java - 使用不相交集在无向图中进行循环检测?

algorithm - 基于数组的不相交集数据结构的时间复杂度

c++ - STL中的Union-Find(或Disjoint Set)数据结构?

c++ - 找出不相交集的数量

algorithm - 找到 x^2+y^2=z^2 解决方案的最佳复杂度

algorithm - 节点加权 DAG 和带更新的最长路径

algorithm - ASM算法解码

测试二维网格上的两条线段是否相邻的算法

data-structures - 如何在不相交的集合数据结构中创建集合并解决并集?