JavaScript 中三个已排序数组的交集
我们要求编写一个 JavaScript 函数,它采用三个顺序递增的整数数组。该函数随后应构造并返回一个数组,其中仅包含在所有这三个数组中都存在的元素。
例如 -
如果输入数组为 -
const arr1 = [4, 7, 8, 11, 13, 15, 17]; const arr2 = [1, 3, 4, 13, 18]; const arr3 = [2, 4, 7, 8, 9, 10, 13];
然后输出应为 -
const output = [4, 13];
实例
代码如下 -
const arr1 = [4, 7, 8, 11, 13, 15, 17]; const arr2 = [1, 3, 4, 13, 18]; const arr3 = [2, 4, 7, 8, 9, 10, 13]; const intersectThree = (arr1 = [], arr2 = [], arr3 = []) => { let curr1 = 0; let curr2 = 0; let curr3 = 0; const res = []; while((curr1 < arr1.length) && (curr2 < arr2.length) && (curr3 < arr3.length)){ if((arr1[curr1] === arr2[curr2]) && (arr2[curr2] === arr3[curr3])){ res.push(arr1[curr1]); curr1++; curr2++; curr3++; } const max = Math.max(arr1[curr1], arr2[curr2], arr3[curr3]); if(arr1[curr1] < max){ curr1++; }; if(arr2[curr2] < max){ curr2++; }; if(arr3[curr3] < max){ curr3++; }; }; return res; }; console.log(intersectThree(arr1, arr2, arr3));
输出
控制台中的输出将为 -
[4, 13]
广告