算法系列-集合

58 阅读1分钟

集合

集合是一个无序且唯一的数据结构。ES6中有集合:Set,集合常用操作:去重、判断某元素是否在集合中、求交集。

JS 实现


js

复制代码

// 去重

const arr = [1, 1, 2, 2]

const arr2 = [...new Set(arr)]

  


// 判断元素是否在集合中

const set = new Set(arr)

const has = set.has(3) // false

  


// 求交集

const set2 = new Set([2, 3])

const set3 = new Set([...set].filter(item => set2.has(item)))

使用场景

  • 场景一:求交集、差集

LeetCode 题目