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/