简体   繁体   English

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

[英]compare values in arrays and if any values match, increment values in first array

I've got this code to check two arrays for any matching values, and if any values do match I ++ everything in array1我有这段代码来检查两个 arrays 是否有任何匹配值,如果有任何值匹配我 ++ array1 中的所有内容

I'm wondering if there is a better way to do this, since I feel like this is a lot of looping, and I'll eventually have 5 arrays i need to compare against each other我想知道是否有更好的方法来做到这一点,因为我觉得这是很多循环,我最终会有 5 个 arrays 我需要相互比较

Any help would be greatly appreciated!任何帮助将不胜感激!

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))

If you know that all arrays are sorted, then you can use the following approach -如果您知道所有 arrays 都已排序,那么您可以使用以下方法 -

CODE -代码 -

 const array1 = [2, 9]; const array2 = [2, 5, 9]; function checkMatch(a, b) { let i = 0, j = 0; while (i < a.length && j < b.length) { if (a[i] === b[j]) { a[i]++; j++; } else if (a[i] < b[j]) { i++; } else j++; } return a; } console.log(checkMatch(array1, array2))

Explanation -解释 -

The above approach will have a time complexity of O(N+M) while your could would have had a time complexity of O(N*M) .上述方法的时间复杂度为O(N+M) ,而您的时间复杂度可能为O(N*M)

In the above function, you are taking advantage of the fact that arrays are sorted.在上面的 function 中,您利用了 arrays 已排序的事实。 So when a[i] < b[j] , you know that you have to increment index i to get a value that can potentially be equal to or greater than b[j] .因此,当a[i] < b[j]时,您知道必须增加索引 i 才能获得可能等于或大于b[j]的值。 The same (but in the reverse way) is the case when a[i] > b[j] .a[i] > b[j]时,情况相同(但相反)。 So, this approach reduces the overall time-complexity of your code and would increases the overall efficiency.因此,这种方法降低了代码的整体时间复杂度,并提高了整体效率。

Hope this helps!希望这可以帮助!

You can use includes method to check if all elements of a list (a) exits in all other arrays you need to compare.您可以使用includes方法检查列表 (a) 的所有元素是否存在于您需要比较的所有其他 arrays 中。 Then you can update the value in list (a)然后您可以更新列表(a)中的值

 function checkMatch(a, b){ for (let i = 0; i < a.length; i++) { if(b.includes(a[i])){ a[i]++; } } return a; }; const array1 = [2, 9]; const array2 = [2, 5, 9]; console.log(checkMatch(array1, array2))

You can simply make use of map here:您可以在这里简单地使用map

 var array1 = [2, 9]; var array2 = [2, 5, 9]; var result = array1.map(n=>(array2.includes(n)? n++: n, n)); console.log(result);

You could take a Set and map the first array with the value plus the check for this value of the set.您可以使用Set和 map 的第一个数组,其中包含该值以及对该集合的该值的检查。

 function checkMatch(a, b) { var values = new Set(b); return a.map(v => v + values.has(v)); } console.log(checkMatch([2, 9], [2, 5, 9]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM