题解 | #查找重复元素#

查找重复元素

https://www.nowcoder.com/practice/871a468deecf453589ea261835d6b78b

高效,简洁
1. 使用Map,一次遍历,时间复杂度为O(n)
2. Map结构用来计数,当元素出现第二次的时候,就是重复的元素

function duplicates(arr) {
    const m = new Map();
    const res = [];
    for (let e of arr) {
        m.set(e, (m.get(e) + 1) || 1);
        if (m.has(e) && m.get(e) == 2) res.push(e);
    }
    return res;
}


全部评论

相关推荐

3 收藏 评论
分享
牛客网
牛客企业服务