硬核数据结构——集合Js
1.集合的基本概念
1.集合:由一组无序且唯一(即不能重复)的项组成的,这个数据结构使用了与集合相同的数学概念。也可以把集合理解为一个既没有重复元素,也没有顺序概念的数组。
2.集合的操作
1.并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合;
2.交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合;
3.差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合;
4.子集:验证一个给定集合是否是另一个集合的子集;
3.集合数据结构实现
export default class Set<T> {
private items: any;
constructor() {
this.items = {};
}
add(element: T) {
if (!this.has(element)) {
this.items[element] = element;
return true;
}
return false;
}
delete(element: T) {
if (this.has(element)) {
delete this.items[element];
return true;
}
return false;
}
has(element: T) {
// return this.items.hasOwnProperty(element);
return Object.prototype.hasOwnProperty.call(this.items, element);
}
values(): T[] {
return Object.values(this.items);
}
union(otherSet: Set<T>) {
const unionSet = new Set<T>();
this.values().forEach(value => unionSet.add(value));
otherSet.values().forEach(value => unionSet.add(value));
return unionSet;
}
intersection(otherSet: Set<T>) {
const intersectionSet = new Set<T>();
const values = this.values();
const otherValues = otherSet.values();
let biggerSet = values;
let smallerSet = otherValues;
if (otherValues.length - values.length > 0) {
biggerSet = otherValues;
smallerSet = values;
}
smallerSet.forEach(value => {
if (biggerSet.includes(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
}
difference(otherSet: Set<T>) {
const differenceSet = new Set<T>();
this.values().forEach(value => {
if (!otherSet.has(value)) {
differenceSet.add(value);
}
});
return differenceSet;
}
isSubsetOf(otherSet: Set<T>) {
if (this.size() > otherSet.size()) {
return false;
}
let isSubset = true;
this.values().every(value => {
if (!otherSet.has(value)) {
isSubset = false;
return false;
}
return true;
});
return isSubset;
}
isEmpty() {
return this.size() === 0;
}
size() {
return Object.keys(this.items).length;
}
clear() {
this.items = {};
}
toString() {
if (this.isEmpty()) {
return '';
}
const values = this.values();
let objString = `${values[0]}`;
for (let i = 1; i < values.length; i++) {
objString = `${objString},${values[i].toString()}`;
}
return objString;
}
}
值得注意的是:我们使用对象表示集合,而不是数组的形式
function set() {
let items = {};
}
add() 向集合添加一个新的项
delete() 从集合中移除一个项
has() 判断这个值是否在集合中,如果在则返回true,否则返回false
values() 返回所有对象值
union() 并集的操作
intersection() 交集的操作
difference() 差集的操作
isSubsetOf() 子集的操作
isEmpty() 判断集合是否为空,
size() 集合内项的数量
clear() 清空集合
toString 将集合内的项转为字符串
注:ECMAScript 2015新增了Set类,与上面方法大同小异。不同的是1.values方法返回Iterator,而不是一个数组。2.size返回size的属性,而非set中存储的值得个数。