【问题标题】:Modification of Intersection of sorted array排序数组的交集的修改
【发布时间】:2013-02-10 01:42:24
【问题描述】:

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

我有两种方法

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

2) 二分查找 - O(m*logn)
[当第二个数组很大时使用]

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

谢谢

【问题讨论】:

  • 如果数组已经排序,您可以简单地以 O(n+m) 并行迭代它们。这应该比哈希表方法更快。
  • 使用两个指针?但是使用这种方法我只能得到两组之间的共同元素。我将不得不再次遍历第一个数组以减去公共元素。
  • 是的,使用两个指针并确保以升序处理两个数组中的元素。这样,您还可以从 a1 中找到不在 a2 中的元素。但是我懒得展示一些示例代码;)

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


【解决方案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(max(N, M))。

【讨论】:

  • 这个例子不正确。用a2 = [0, 2, 4, 5] 试试,它不会返回任何结果。
  • 您也需要增加 a2_index 计数器...您没有考虑 a2[index]>a1[index] 的另一种情况
猜你喜欢
  • 2011-01-24
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多