排序数组交集的修改

时间:2013-02-24 23:40:22

标签: algorithm sorting tree complexity-theory binary-search

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

我有两种方法

1)Hashtable - O(m + n)
            [当第二个数组很小时使用]

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

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

谢谢

1 个答案:

答案 0 :(得分:1)

只需并行迭代它们。

这是一个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(最大(N,M))。