05-数据结构-集合

 集合

集合是一种不允许值重复的顺序数据结构。

集合是由无序切唯一的项组成。使用了与有限集合相同的数学概念,但是运用于计算机科学的数据结构中。

在这里我们要实现类似于数学中集合的相关运算:

  • 创建集合
  • 添加、移除、判断等基本方法
  • 交集、并集、差集、子集等运算
// 集合
export class Set {
  items: { [key: string]: any };
  constructor() {
    this.items = {};
  }

  // 判断是否有某一项
  has(element: any) {
    // return element in this.items;
    return Object.prototype.hasOwnProperty.call(this.items, element);
  }

  // 给集合中添加一项
  add(element: any) {
    if (!this.has(element)) {
      // 用element作为键,方便访问和使用
      this.items[element] = element;
      return true;
    }
    return false;
  }

  // 移除一项
  remove(element: any) {
    if (this.has(element)) {
      delete this.items[element];
      return true;
    }
    return false;
  }

  // 清空
  clear() {
    this.items = {};
  }

  // 返回当前集合的元素个数
  size() {
    return Object.keys(this.items).length;
  }

  // 返回当前集合的value
  values() {
    return Object.values(this.items);
  }

  // 并集
  union(otherSet: any) {
    const res = new Set();
    this.values().forEach((item) => res.add(item));
    otherSet.values().forEach((item) => res.add(item));
    return res;
  }

  // 交集
  intersection(otherSet: any) {
    const res = new Set();
    this.values().forEach((item) => {
      if (otherSet.has(item)) {
        res.add(item);
      }
    });
    return res;
  }

  // 差集
  differenceSet(otherSet: any) {
    const res = new Set();
    this.values().forEach((item) => {
      if (!otherSet.has(item)) {
        res.add(item);
      }
    });
    return res;
  }

  // 子集
  subset(otherSet: any) {
    if (this.size() > otherSet.size()) {
      return false;
    }
    return this.values().every((item) => otherSet.has(item));
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值