数据结构与算法之集合(Set)

175 阅读1分钟

集合

1. 概念:

集合(Set) 是一种包含不同元素的数据结构。集合中的元素称为成员

2. 集合中最重要的两个特点:

  • 集合中的成员是无序;

  • 集合中不存在相同成员;

即:无序且唯一。

3. 集合在数学中的概念:

集合的概念,如数学中一个由大于或等于0的整数组成的自然数集合, N={0,1,2,...}

还有如空集,表示不包含任何元素的集合。

对集合一些操作:

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

实现:

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;
    }
    // 并集
    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;
    }
    // 交集
    intersection(otherSet) {
        const intersectionSet = new Set();
        this.values.forEach((v, i) => {
            if (otherSet.has(v)) {
                intersectionSet.add(v);
            }
        });
        return intersectionSet;
    }
    // 差集,A-B 存在于A中且不存在与B中
    difference(otherSet) {
        const differenceSet = new Set();
        this.values.forEach((v, i) => {
            if (!otherSet.has(v)) {
                differenceSet.add(v);
            }
        });
        return differenceSet;
    }
    // 子集,A 包含于 B
    subset(otherSet) {
        if (this.size > otherSet.size) {
            return false;
        } else {
            return !this.values.some(v => !otherSet.has(v));
        }
    }
    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); // []