algorithm - 排序数组交集的修改

标签 algorithm sorting tree complexity-theory binary-search

我遇到了这个问题 - 输入 - 我得到了两个排序数组 a1 和 a2。我需要找到第二个数组中不存在的元素。

我有两种方法

1) 哈希表 - O(m+n)
[当第二个数组较小时使用]

2) 二进制搜索 - O(m*logn)
[当第二个数组很大时使用]

还有其他时间复杂度更好的方法吗?

谢谢

最佳答案

只需并行迭代它们即可。

这是一个 JavaScript 示例:

var a1 = [1, 2, 3, 4, 5, 6, 7, 9];
var a2 = [0, 2, 4, 5, 8];

findNotPresent(a1, a2); // [1, 3, 6, 7, 9]


function findNotPresent(first, second) {
    var first_len = first.length;
    var first_index = 0;

    var second_len = second.length;
    var second_index = 0;

    var result = [];

    while (first_index < first_len && second_index < second_len) {
        if (first[first_index] < second[second_index]) {
            result.push(first[first_index]);
            ++first_index;
        }
        else if (first[first_index] > second[second_index]) {
            ++second_index;
        }
        else {
            ++first_index;
            ++second_index;
        }
    }

    while (first_index < first_len) {
        result.push(first[first_index++]);
    }

    return result;
}

我相信它会花费 O(max(N, M))。

关于algorithm - 排序数组交集的修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15058066/

相关文章:

javascript - 在函数中拒绝不返回错误

orm - 如何在 ColdFusion 中对内存中的 ORM 对象数组进行排序和过滤?

c# - 二叉搜索树的递归函数实现

c# - 如何找到我的 Gin 问题的解决方案?

algorithm - 队列中的前 n 个元素

algorithm - d-堆删除算法

xml - XSL Sort 将小写字母与大写字母分开处理

java - 对可比较接口(interface)的数组进行排序

javascript - 使用 d3v4 .stratify() 嵌套 JSON

python - 如何给 `ete3` 树上的树叶上色? ( python 3)