- 无序唯一的数据结构
- ES6中有集合,名为 Set
- 集合的常用操作:去重、判断某元素是否在集合中、求交集
- 如需了解Set及其操作可看我这篇文章:ES6 Set和Map数据结构以及Symbol数据类型 - 掘金 (juejin.cn)
const arr1 = [1, 1, 1, 2, 2, 3];
// 去重
const uniqueArr = [...new Set(arr1)]; // [1, 2, 3]
// 判断元素是否在集合中
const set1 = new Set(uniqueArr);
set1.has(2); // true
1、LeetCode: 349.两个数组的交集
// 时间复杂度 O(n^2) n为数组长度
// 空间复杂度 O(n) n为去重后的数组长度
const intersection = function(nums1, nums2) {
return [...new Set(nums1)].filter(item => new Set(nums2).has(item));
};