数据结构-集合

155 阅读1分钟

今天学习的是数据结构中的集合.它的概念很类似数学中集合的概念,有并集,交集,差级,补集和子集的概念。集合这个数据结构相对于其他数据结构较为简单,以下是我用对象来实现的集合以及集合的操作:

    class Set {
          // 属性
          items = {}
          // 方法
          // 添加元素
          add(value) {
            // 将元素添加到集合
            this.items[value] = value
            return true
          }
          // 判断是否包含某个元素
          has(value) {
            return this.items[value] === value
          }
          // 移除元素
          remove(value) {
            if (!this.has(value)) return false
            delete this.items[value]
            return true
          }
          // 清空集合
          clear() {
            this.items = {}
          }
          // 返回集合的大小
          size() {
            return Object.keys(this.items).length
          }
          // 返回集合中所有的元素
          values() {
            return Object.values(this.items)
          }
          // 并集
          union(otherSet) {
            const unionSet = new Set()
            this.values().forEach((value) => unionSet.add(value))
            otherSet.values().forEach((value) => unionSet.add(value))
            return unionSet
          }
          // 交集
          intersection(otherSet) {
            const intersectionSet = new Set()
            this.values().forEach((value) => {
              if (otherSet.has(value)) {
                intersectionSet.add(value)
              }
            })
            return intersectionSet
          }
          // 差集
          difference(otherSet) {
            const differenceSet = new Set()
            this.values().forEach((value) => {
              if (!otherSet.has(value)) {
                differenceSet.add(value)
              }
            })
            return differenceSet
          }
          // 子集
          subset(otherSet) {
            if (this.size() > otherSet.size()) return false
            return this.values().every((value) => otherSet.has(value))
          }
}