javascript - 比较两个数组和唯一值计数?

标签 javascript arrays compare

function commonElement(array1, array2) {
  var count = 0;
  for (var i = 0; i < array1.length; i++) {
    for (var j = 0; j < array2.length; j++) {
      if (array1[i] === array2[j]) {
        count++;
      }
    }
  }
  return count
}

console.log(commonElement([5, 2, 8, 9, 4, 7], [3, 2, 9, 5, 7]))

*当我将非唯一值放入我的数组时,输出为 *

console.log(commonElement([5,2,2,8,9,4,7],[3,2,9,5,7])) //output is 5

但我希望我的输出是 4,因为 2,2 与 2 相比,它唯一的 2 计数输出是 5

最佳答案

首先克隆其中一个数组(以避免变异),然后遍历另一个数组,使用 findIndex 在克隆的数组中找到匹配的元素。如果存在,则拼接出来,计数加1:

function commonElement(array1, array2) {
  const arr1 = array1.slice();
  let count = 0;
  for (const val of array2) {
    const index = arr1.indexOf(val);
    if (index !== -1) {
      count++;
      arr1.splice(index, 1);
    }
  }
  return count;
}
console.log(commonElement([5, 2, 2, 8, 9, 4, 7], [3, 2, 9, 5, 7]))
console.log(commonElement([2, 2], [2, 2]))

要将计算复杂度从 O(n^2) 降低到 O(n),请先将其中一个数组计数到一个对象中:

function commonElement(array1, array2) {
  const arr1Counts = {};
  for (const val of array1) {
    arr1Counts[val] = (arr1Counts[val] || 0) + 1;
  }
  let count = 0;
  for (const val of array2) {
    if (arr1Counts[val]) {
      arr1Counts[val]--;
      count++;
    }
  }
  return count;
}
console.log(commonElement([5, 2, 2, 8, 9, 4, 7], [3, 2, 9, 5, 7]))
console.log(commonElement([2, 2], [2, 2]))

关于javascript - 比较两个数组和唯一值计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212557/

相关文章:

javascript - 如何从vue js中的数组中删除选定的数据?

c - 涉及结构体和数组的段错误,但不分开

java - 为什么java数组的最大大小是Integer.MAX_VALUE/7?

compare - SAS proc 比较中的 BY 语句

c++ - 如果数组全为 0(或 false),我可以在 C(++) 中检查吗?

c - C语言中如何比较多个字符串

javascript - 为什么我的 $ (".selector").show(900);代码只在浏览器控制台中启动,但从不在助手中启动?

javascript - Div 高度并不总是返回相同的数字

javascript - 在 Javascript 中创建的 Canvas 语音气泡 -> 测量文本高度?

c - 将数组放入函数中并且数组的奇数不起作用