数据结构 - 集合

集合

集合是由一组无序且唯一(不能重复)的项组成的。这个数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中。

使用JavaScript创建一个集合类:

class Set {

    constructor() {
        this.items = {}
    }

    has(value) {
        return this.items.hasOwnProperty(value)
    }

    add(value) {
        if (!this.has(value)) {
            this.items[value] = value
            return true
        }     
        return false
    }

    remove(value) {
        if (this.has(value)) {
            delete this.items[value]
            return true
        }
        return false
    }

    get size() {
        return Object.keys(this.items).length
    }

    get values() {
        return Object.keys(this.items)
    }
}

使用集合类:

const set = new Set()
set.add(1)
console.log(set.values)  // ["1"] 
console.log(set.has(1))  // true 
console.log(set.size) // 1 
set.add(2) 
console.log(set.values)  // ["1", "2"] 
console.log(set.has(2))  // true 
console.log(set.size) // 2 
set.remove(1) 
console.log(set.values) // ["2"] 
set.remove(2) 
console.log(set.values) // []

对集合可以进行如下操作:

  • 并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合。
  • 交集:对于给定的两个集合,返回一个包含两个集合中Р有元素的新集合。
  • 差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合。
  • 子集:求证一个给定集合是否是另一集合的子集。

并集

并集的数学概念:集合A和B的并集,表示为A∪B,定义如下:A∪B = { x | x∈A ∨ x∈B },意思是x(元素)存在于A中,或x存在于B中。如图:
在这里插入图片描述
我们基于刚才的 Set 类实现一个并集方法:

union(otherSet) {
    const unionSet = new Set()
    this.values.forEach((v, i) => unionSet.add(this.values[i]))
    otherSet.values.forEach((v, i) => unionSet.add(otherSet.values[i]))
    return unionSet
}

交集

并集的数学概念:集合A和B的交集,表示为A∩B,定义如下:A∩B = { x | x∈A ∧ x∈B },意思是x(元素)存在于A中,且x存在于B中。如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FVexBOih-1584444591874)(C:\Users\lin\AppData\Roaming\Typora\typora-user-images\1584363809538.png)]

我们基于刚才的 Set 类实现一个交集方法:

intersection(otherSet) {
    const intersectionSet = new Set()
    this.values.forEach((v, i) => {
        if (otherSet.has(v)) {
            intersectionSet.add(v)
        }
    })
    return intersectionSet
}

差集

差集的数学概念:集合A和B的差集,表示为A-B,定义如下:A-B = { x | x∈A ∧ x∉B },意思是x(元素)存在于A中,且不x存在于B中。如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AIaaIwBx-1584444591876)(C:\Users\lin\AppData\Roaming\Typora\typora-user-images\1584363862018.png)]

我们基于刚才的 Set 类实现一个差集方法:

difference(otherSet) {
    const differenceSet = new Set()
    this.values.forEach((v, i) => {
        if (!otherSet.has(v)) {
            differenceSet.add(v)
        }
    })
    return differenceSet
}

子集

子集的数学概念:集合A是B的子集,或者说集合B包含了集合A,如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zPjByMD6-1584444591877)(C:\Users\lin\AppData\Roaming\Typora\typora-user-images\1584363899399.png)]

我们基于刚才的 Set 类实现一个子集方法:

subset(otherSet) {
    if (this.size > otherSet.size) {
        return false
    } else {
        return !this.values.some(v => !otherSet.has(v))
    } 
}

学习于:JavaScript中的数据结构与算法学习

发布了60 篇原创文章 · 获赞 121 · 访问量 7539

猜你喜欢

转载自blog.csdn.net/weixin_46124214/article/details/104929093