集合

  • 一种无序且唯一的数据结构
  • ES6增加了集合,Set
  • 常用操作:去重 判断是否在集合中,求交集,差集
1
2
3
4
5
6
7
8
9
10
11
12
// 去重
const arr = [1,2,3,4,4,4,4]
const arr2 = [...new Set(arr)]

// 判断是否在集合中
const set = new Set(arr)
const has = set.has(2)

// 求交集
const set1 = new Set([1,2,3,4])
const set2 = new Set([3,4,5,6])
const set3 = new Set([...set1].filter(e => set2.has(e))) // 将其中一个变成数组,另一个has,最终结果转为Set

题目 两个数组的交集

https://leetcode-cn.com/problems/intersection-of-two-arrays/

时间复杂度:O(n^2)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function(nums1, nums2) {
return [...new Set(nums1.filter(e => nums2.includes(e)))]
};

JavaScript中Set的一些操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
let my = new Set()

my.add(1) // 正常加入
my.add(2) // 正常加入
my.add(2) // set保证不会重复,依旧只有一个2
my.add('313') // 正常加入
let o = {
a: 1
}
my.add(o) // 正常加入
my.add({ // 正常加入
a: 1
})

const has1 = my.has({
a: 1
}) // 返回false 引用类型不在内存的同一个地方

const has2 = my.has(o) // 返回true
console.log(has1);

my.delete(1) // 正常删除

for (const item of my) { // 迭代函数 这个不使用my 使用my.values my.keys 都可以 都是一样的
console.log(item);
}