内容大纲

集合

huan_kong

292字小于1分钟

2023-11-30

介绍

元素是无序的, 不能重复的

优点: 存取方便

缺点: 不能存重复的数据

函数讲解

image-20231205104723540

union

  • 创建一个新的合集
  • 循环当前集合还有需要合并的集合
  • 把所有数据插入到这个新创建的集合上

intersection

  • 创建一个新的合集
  • 循环传入的集合判断当前集合是否存在
  • 把存在的数据插入到这个新创建的集合上

difference

  • 创建一个新的合集
  • 循环传入的集合判断当前集合是否存在
  • 把不存在的数据插入到这个新创建的集合上

subSet

方案1

  • 循环传入的集合判断当前集合是否存在, 如果不存在就返回 false
  • 在循环结束的最后返回 true

方案2

  • 创建一个计数
  • 循环传入的集合判断当前集合是否存在, 如果存在 计数+1
  • 如果计数等于传入的集合就返回 true 否则返回 false

TS实现

namespace 集合 {
  class Set {
    #values: { [key: string]: any } = {}

    add(value: any) {
      if (this.has(value)) return false
      return (this.#values[value] = value)
    }

    remove(value: any) {
      if (!this.has(value)) return false
      return delete this.#values[value]
    }

    has(value: any) {
      return this.#values[value] !== undefined
    }

    clear() {
      return (this.#values = {})
    }

    size() {
      return Object.keys(this.#values).length
    }

    values() {
      return Object.values(this.#values)
    }

    toString() {
      return Object.values(this.#values).join(' , ')
    }

    union(otherSet: Set) {
      const unionSet = new Set()

      for (const value of this.values()) {
        unionSet.add(value)
      }

      for (const value of otherSet.values()) {
        unionSet.add(value)
      }

      return unionSet
    }

    intersection(otherSet: Set) {
      const intersectionSet = new Set()

      for (const value of otherSet.values()) {
        if (this.has(value)) intersectionSet.add(value)
      }

      return intersectionSet
    }

    difference(otherSet: Set) {
      const differenceSet = new Set()

      for (const value of otherSet.values()) {
        if (!this.has(value)) differenceSet.add(value)
      }

      return differenceSet
    }

    subSet(otherSet: Set) {
      // 方案2
      // let count = 0
      // for (const value of otherSet.values()) {
      //   if (this.has(value)) count++
      // }
      // return count === otherSet.size()

      // 方案1
      for (const value of otherSet.values()) {
        if (!this.has(value)) return false
      }

      return true
    }
  }
}