【问题标题】:How to code a non brutal search如何编写非残酷搜索
【发布时间】:2017-02-25 20:53:58
【问题描述】:

我正在编写一个 javascript sn-p 来搜索两个数组之间的匹配项。我知道如何粗暴地搜索它(数组需要一个数字输入,搜索其他数组的每个值以查看它们是否匹配一遍又一遍),但它的效率非常低。如果有人知道一种在两个数组之间搜索共同值的方法,以便尽可能缩短时间,请帮助我。

var 1 = ["bob", "Sophie"];
var 2 = ["Sherry", "Gerard", "Joseph"];

for(var i; i <= 1.length; i++){

switch(1[i]){

case 1[i] === 2[1]:
console.log("They match!");

break;

case 1[i] === 2[2]:
console.log("They match!");

break;

case 1[i] === 2[3]:
console.log("They match!");

break;

case default:
console.log("No matches found.");

}
}
}

PS 不要介意语法错误,这是代码的“草稿”。我只是为了让你明白我的意思。

【问题讨论】:

  • 发布一个你尝试过的例子。
  • 阵列有多大?本能地说,对数组进行排序然后搜索它会是最快的(对于较大的数组)。
  • @IvanModric 数组将非常大,平均将存储大约 200 个值。如何对数组进行排序?
  • 你可以用谷歌搜索“快速排序”。这似乎是一个不错的实现,但我现在在手机上,所以我无法正确编辑评论或检查代码:gist.github.com/paullewis/1981455

标签: javascript arrays


【解决方案1】:

您可以使用哈希表并迭代第一个数组来创建一个表,然后只用一个循环过滤第二个数组。

Complexity: O(n + m)

var array1 = ["bob", "Sophie"],
    array2 = ["Sherry", "Gerard", "Joseph"],
    hash = Object.create(null),
    found;

array1.forEach(function (a) {
    hash[a] = true;
});

found = array2.filter(function (a) {
    return hash[a];
});
console.log(found);

array2.push("Sophie");
found = array2.filter(function (a) {
    return hash[a];
});
console.log(found);

ES6 与 Set

var array1 = ["bob", "Sophie"],
    array2 = ["Sherry", "Gerard", "Joseph"],
    aSet = new Set(array1),
    found;

found = array2.filter(a => aSet.has(a));
console.log(found);

array2.push("Sophie");
found = array2.filter(a => aSet.has(a));
console.log(found);

【讨论】:

  • ... 假设哈希查找/插入是 O(1)。理论上,他们宁愿按 O(log(n))
  • 实际上表的构建是 O(n) 加上查找值。
【解决方案2】:

如果我理解正确,你需要找到共同的元素。然后我将使用 Underscore.Js 外部库(如下面的 sn-p 所示)或以下链接中建议的其他解决方案 How to find common elements only between 2 arrays in jquery

var array1 = ["bob", "Sophie"];
var array2 = ["bob", "Gerard", "Joseph"];

alert(_.intersection(array1, array2));
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2016-07-21
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2018-12-02
    相关资源
    最近更新 更多