Advanced-Frontend / Daily-Interview-Question

我是依扬(木易杨),公众号「高级前端进阶」作者,每天搞定一道前端大厂面试题,祝大家天天进步,一年后会看到不一样的自己。
https://muyiy.cn/question/
27.41k stars 3.29k forks source link

第 142 题:(算法题)求多个数组之间的交集 #293

Open igoryaodev opened 5 years ago

igoryaodev commented 5 years ago

算法

Yangfan2016 commented 2 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);
};