双指针查询写法(GPT生成):
function findIntersection(arrays) {
if (arrays.length === 0) {
return [];
}
const sortedArrays = arrays.map(arr => [...arr].sort((a, b) => a - b));
const intersection = [];
const pointers = new Array(sortedArrays.length).fill(0);
let done = false;
while (!done) {
const values = pointers.map((pointer, index) => sortedArrays[index][pointer]);
const minValue = Math.min(...values);
const maxValue = Math.max(...values);
if (minValue === maxValue) {
intersection.push(minValue);
for (let i = 0; i < pointers.length; i++) {
pointers[i]++;
}
} else {
const minPointer = values.findIndex(value => value === minValue);
if (minPointer === -1) {
break;
}
pointers[minPointer]++;
}
done = pointers.some((pointer, index) => pointer === sortedArrays[index].length);
}
return intersection;
}
const arrays = [
[1, 3, 4, 6, 7, 9],
[2, 3, 4, 7, 9, 10],
[3, 4, 7, 8, 9, 11]
];
const intersection = findIntersection(arrays);
console.log(intersection);