菩提树下叶撕阳。

文章 评论 浏览 29

菩提树下叶撕阳。 2022-05-04 13:54:34

Clarify

Since the description kind of loose, So Let's make it clear.

Suppose that, all the list are unique , eg: [1,2,2,3] is not allow.Otherwise the solution could be quiet ugly.

Concise Solution - reduce

initially, we can set the answer to be the very first item of the list.

eg: [1,2,3], [1,2,3,5], [1] , we take [1,2,3] as the initial value(the answer can't be greater than it). then we keep filtering repeatedly

If U'r not familar with reduce, PLZ check the MDN Doc

const intersection = (...list) => list.reduce((acc, cur) => acc.filter(ele => cur.includes(ele)))

// test
intersection([1,2,3], [1,2,3,5], [1]) // [1]

More efficient and Easy to understand

  • track the repeating count, store into Map as [k=item, v=count]
  • finally, remove all the items which repeating counts not equals to the size of the list(WHY?)
function intersection(...list) {
  const mapper = new Map();
  const res = [];
  for (ele of list) {
    for (n of ele) {
      if (mapper.get(n) === void 0) {
        mapper.set(n, 1);
      } else {
        mapper.set(n, mapper.get(n) + 1);
      }
    }
  }

  for ([k, cnt] of mapper.entries()) {
    if (cnt === list.length) res.push(k);
  }

  return res;
}

// test
intersection([1,2,3], [1,2,3,5], [1]) // [1]

Thanks for your reading, if like it, Give Me a thumb up

第 142 题:算法题 - 求多个数组之间的交集

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文