集合
集合是一种不允许值重复的顺序数据结构。
集合是由无序切唯一的项组成。使用了与有限集合相同的数学概念,但是运用于计算机科学的数据结构中。
在这里我们要实现类似于数学中集合的相关运算:
- 创建集合
- 添加、移除、判断等基本方法
- 交集、并集、差集、子集等运算
// 集合
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));
}
}