前端之数据结构(三)

379 阅读2分钟

这是我参与8月更文挑战的第四天,活动详情查看:8月更文挑战

承接上文,继续,今天的集合和字典介绍。

集合

  • 一种无序且唯一的数据结构。

  • 在ES6中就有集合,名Set。

  • 集合的常用操作:去重、判断某元素是否在集合中、求交集等等...

去重

const arr = [1,1,2,2,3,3]
const arr2 = [...new Set(arr)]

console.log(arr2)
// [1, 2, 3]

判断元素是否在集合中

const set = new Set(arr)
const has = set.has(2)

console.log(has)
// true

求交集

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

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

console.log(set3)
// [2]

求差集

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

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

console.log(set3)
// [1]

Set基本操作

  • 使用 Set 对象:new、add、delete、has、size

  • 迭代 Set:多种迭代方法、SetArray 互转、求交集/差集

  • 迭代 Setkey

const mySet = new Set([1,2,3,4,5])

for (let key of mySet) console.log(key);

// 1 2 3 4 5
  • 迭代 Setvalue
const mySet = new Set([1,2,3,4,5])

for (let key of mySet.values) console.log(key);

// 1 2 3 4 5
  • 迭代 Setkey 和 value
const mySet = new Set([1,2,3,4,5])

for (let [key, value] of mySet.entries()) 

console.log(key, value);

// 1 1 2 2 3 3 4 4 5 5

我们可以发现 Setkey 和 value是一样的。

  • Set 转 Array
const mySet = new Set([1,2,3,4,5])

const myArr = [...mySet]

const myArr2 = Array.from(mySet)

字典

  • 与集合类似,字典也是一种存储唯一值的数据结构,但它是以 键值对 的形式来存储。

  • 在ES6中就有集合,名Map。

  • 字典的常用操作:键值对的增删改查。

Set的基本操作

const map = new Map()
// 增
map.set('你', '好')
// 删
map.delete('你')
map.clear() // 清空
// 改
map.set('你', '不好')
// 查
map.get('你')

时间复杂度都是 O(1)。

求交集

function intersection(nums1: number[], nums2: number[]): number[] {
    const map = new Map()
    nums1.forEach(e => {
        map.set(e, true)
    })
    const res = []
    nums2.forEach(e => {
        if(map.get(e)) {
            res.push(e)
            map.delete(e)
        }
    })
    return res
};

今天就到这里,明天见!