Open igoryaodev opened 5 years ago
https://leetcode.cn/problems/intersection-of-multiple-arrays/submissions/
// 法一: reduce 结合 includes 去重
/**
* @param {number[][]} nums
* @return {number[]}
*/
var intersection = function (nums) {
return nums.reduce((prev, cur) => prev.filter(item => cur.includes(item))).sort((a, b) => a - b);
};
// 法二: map 统计每个元素的个数,如果个数等于 多数组的总数 ,则认为存在交集
/**
* @param {number[][]} nums
* @return {number[]}
*/
var intersection = function (nums) {
const map = new Map;
const res = [];
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums[i].length; j++) {
const item = nums[i][j];
map.set(item, (map.get(item) || 0) + 1);
}
}
for (let [key, value] of map) {
if (value === nums.length) {
res.push(key);
}
}
return res.sort((a, b) => a - b);
};
算法