【问题标题】:What is the fastest order of magnitude that array subtraction can be implemented in JavaScript?数组减法可以在 JavaScript 中实现的最快数量级是多少?
【发布时间】:2012-03-31 15:07:56
【问题描述】:

我想要一个函数,减法,它将接受两个数组,并返回数组 1 中不在数组 2 中的所有元素。

这可以在 js 中实现的最快速度是多少?是o(n)吗?

【问题讨论】:

  • 这些数组中有什么?它们是深层对象还是仅仅是值?
  • 见这里 - stackoverflow.com/questions/2963281/… 。因为你必须在 O(n) 时遍历两个数组
  • 请注意,如果它们都已排序,则只有O(n),否则您最终会得到O(n^2) 操作。
  • 它是 o(n^2) 因为 indexOf 也是 o(n)。我不确定排序是否会使其成为 O(n)
  • @regality 和 Raynos ~ 显然它可以在 o(n) 中完成 .. 见阿德里安的回答

标签: javascript arrays performance algorithm


【解决方案1】:

除非您想将数组限制为可以序列化为字符串的对象,否则通常无法解决 O(n) 的问题

function substract(one, two) {
    var result = []
    for (var i = 0, len = one.length; i < len; i++) {
        var value = one[i]
        if (two.indexOf(value) === -1) {
            result.push(value)
        }
    }
    return result
}

或者如果你想使用数组迭代器

function substract(one, two) {
    return one.filter(function (value) {
        return two.indexOf(value) === -1
    })
}

【讨论】:

  • 感谢您抽出宝贵时间做出回应,但使用 indexOf 可以保证最少 n^2 运行时间。
【解决方案2】:

另一种选择,更快的 O(n) 时间,但双倍内存(仍然是线性的),是创建自己的 hashmap 实现。

创建一个哈希函数。循环遍历一个数组并散列所有元素。将(哈希,对象)对存储在另一个数组中,称为哈希数组。现在遍历数组 2,并对每个元素进行哈希处理。让散列成为散列数组中的位置,这样你就可以看到是否有冲突。如果您有冲突,请检查哈希数组中的对象是否与当前数组中的对象相同(您正在循环)。

【讨论】:

  • 在js实现中,还是o(n)吗?
  • @ZacharyBurt 是的;毕竟,您正在执行实施,因此您可以控制它。它是 2 个 for 循环:o(n) + o(n) = n(n) 运行时。你需要额外的 o(n) 内存来存储 hashmap,这又是 2*o(n)=o(n)
【解决方案3】:

这是一个哈希表实现(使用 javascript 对象作为哈希),它使用更大的数组比使用 indexOf() 的蛮力查找快 100 倍以上(在 Chrome 中)。

function subtract3(one, two) {
    var hash = {}, result = [], i, len;
    // fill hash with members of second array for easy lookup
    for (i = 0, len = two.length; i < len; i++) {
        hash[two[i]] = true;
    }

    // cycle through first array and find ones that are not in two
    for (i = 0, len = one.length; i < len; i++) {
        if (!(one[i] in hash)) {
            result.push(one[i]);
        }
    }
    return(result);
}

这是一个 jsperf 测试,将这个选项与其他几个选项进行比较:http://jsperf.com/array-subtraction

【讨论】:

  • @Raynos - 是的,这是正确的。我假设这是一个字符串或数字数组。 OP没有指定。
猜你喜欢
  • 2014-05-09
  • 2011-11-30
  • 2015-11-18
  • 2019-11-22
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多