javascript 公地在三阵

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 公地在三阵相关的知识,希望对你有一定的参考价值。

// Find common elements in three sorted arrays

let findCommons = (a1, a2, a3) => {
	// init stating indexes for a1, a2 and a3
	let i = j = k = 0;

	// iterate through three arrays while all arays have elements
	while (i < a1.length && j < a2.length && k < a3.length) {
		// If x = y and y = z, print any of them and move ahead in all arays
		if (a1[i] == a2[j] && a2[j] == a3[k]) {
			console.log(a1[i] + '');
			i++; j++; k++;
		} else if (a1[i] < a2[j]) { // x < y
			i++;
		} else if (a2[j] < a3[k]) { // y < z
			j++;
		} else { // We reach here when x > y and z < y, i.e., z is smallest
			k++;
		}
	}
}


let a1 = [1, 5, 10, 20, 40, 80];
let a2 = [6, 7, 20, 80, 100];
let a3 = [3, 4, 15, 20, 30, 70, 80, 120];

findCommons(a1, a2, a3); // 20, 80

以上是关于javascript 公地在三阵的主要内容,如果未能解决你的问题,请参考以下文章