已知两个数组,均为正序排列,从小到大排列,求两个数组的交集和差集。
let arr1 = [1, 3, 5, 6];
let arr2 = [2, 4, 6];
// 查询交集
function getArr(a, b) {
let res = []
if (a.length < 1 || b.length < 1) return
for (let i = 0; i < a.length; i++) {
if (b.indexOf(a[i]) !== -1) {
res.push(a[i])
}
}
return res
}
// 查询交集和差集 ---双指针
function ar(a, b) {
let res = [];
let res2 = [];
//定义两个索引值
let index1 = 0,
index2 = 0;
// for循环写法
// for (; a.length > index1 && b.length > index2;) {
// if (a[index1] === b[index2]) {
// res.push(a[index1])
// index1++;
// index2++;
// } else if (a[index1] > b[index2]) {
// res2.push(b[index2])
// index2++;
// } else {
// res2.push(a[index1])
// index1++;
// }
// }
//while循环
while (a.length > index1 && b.length > index2) {
if (a[index1] === b[index2]) { //如果a[0]===b[0],push到交集;更新索引位置
res.push(a[index1]);
index1++;
index2++;
} else if (a[index1] < b[index2]) { //如果a[0]<b[0],把a[0]放到差集,比较a[1]和b[0]
res2.push(a[index1])
index1++;
} else { // 如果a[0]>b[0],把b[0]放到差集中,更新索引b[1]去和a[0]比较
res2.push(b[index2])
index2++;
}
}
return { res, res2 }
}
console.log(ar(arr1, arr2))
console.log(getArr(arr1, arr2))
每天进步一点点!