比较数组中的值,如果任何值匹配,则增加第一个数组中的值

我有这段代码来检查两个数组是否有任何匹配的值,如果有任何值匹配我 ++ array1 中的所有内容


我想知道是否有更好的方法来做到这一点,因为我觉得这是很多循环,我最终会有 5 个数组需要相互比较


任何帮助将不胜感激!


const array1 = [2, 9];


const array2 = [2, 5, 9];


function checkMatch(a, b) {

  for (let i = 0; i < a.length; i++) {

    for (let e = 0; e < b.length; e++) {

      if (a[i] === b[e]) a[i]++;

    }

  }

  return a;

}


console.log(checkMatch(array1, array2))


德玛西亚99
浏览 127回答 4
4回答

慕容708150

您可以使用 aSet并将第一个数组映射到该值以及对该集合的该值的检查。function checkMatch(a, b) {&nbsp; &nbsp; var values = new Set(b);&nbsp; &nbsp; return a.map(v => v + values.has(v));}console.log(checkMatch([2, 9], [2, 5, 9]));

千万里不及你

你可以简单地利用map这里:var array1 = [2, 9];var array2 = [2, 5, 9];var result = array1.map(n=>(array2.includes(n) ? n++ : n, n));console.log(result);

慕森卡

您可以使用includes方法检查列表 (a) 的所有元素是否存在于您需要比较的所有其他数组中。然后您可以更新列表(a)中的值function checkMatch(a, b){&nbsp; &nbsp; for (let i = 0; i < a.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(b.includes(a[i])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i]++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; return a;};const array1 = [2, 9];const array2 = [2, 5, 9];console.log(checkMatch(array1, array2))

料青山看我应如是

如果您知道所有数组都已排序,那么您可以使用以下方法 -代码 -const array1 = [2, 9];const array2 = [2, 5, 9];function checkMatch(a, b) {&nbsp; let i = 0,&nbsp; &nbsp; j = 0;&nbsp; while (i < a.length && j < b.length) {&nbsp; &nbsp; if (a[i] === b[j]) {&nbsp; &nbsp; &nbsp; a[i]++;&nbsp; &nbsp; &nbsp; j++;&nbsp; &nbsp; } else if (a[i] < b[j]) {&nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; } else j++;&nbsp; }&nbsp; return a;}console.log(checkMatch(array1, array2))解释 -上述方法的时间复杂度为 ,O(N+M)而您的时间复杂度可能为O(N*M).在上述函数中,您利用了数组已排序这一事实。因此,当 时a[i] < b[j],您知道必须增加索引 i 才能获得可能等于或大于 的值b[j]。当 时,情况相同(但相反)a[i] > b[j]。因此,这种方法降低了代码的整体时间复杂度,并提高了整体效率。希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript