文章 评论 浏览 29
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.
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
filtering
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]
repeating count
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
文章 0 评论 0
接受
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
repeatedlyMore efficient and Easy to understand
repeating count
, store into Map as [k=item, v=count]Thanks for your reading, if like it, Give Me a thumb up
第 142 题:算法题 - 求多个数组之间的交集