js获取数组的交集和差集

已知两个数组,均为正序排列,从小到大排列,求两个数组的交集和差集。

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))

每天进步一点点!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值