集合

Set集合的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Set {
constructor() {
this.set = { "a": 1, __proto__: { b: 1 } };
}
has(element) {
return Object.prototype.hasOwnProperty.call(this.set, element)
}
add(element) {
if (!this.has(element)) {
this.set[element] = element;
return true;
}
return false;
}
delete(element) {
if (this.has(element)) {
Reflect.deleteProperty(this.set, element)
return true;
}
return false;
}
clear() {
this.items = {};
}
size() {
return Reflect.ownKeys(this.set).length
}
values() {
return Object.values(this.items);
}
}

集合运算

  • 并集
1
2
3
4
5
6
7
8
9
10
function union(A, B) {
const set = new Set();
A.values().forEach(v => {
set.add(v)
});
B.values().forEach(v => {
set.add(v)
});
return set;
}
  • 交集
1
2
3
4
5
6
7
8
9
function intersection(A, B) {
const set = new Set();
A.values().forEach(item => {
if (B.has(item)) {
set.add(item);
}
});
return set;
}
  • 差集

A与B的差集表示存在于A,但是不存在于B

B与A的差集表示存在于B,但是不存在于A

1
2
3
4
5
6
7
8
9
function differenceSet(A, B) {
const set = new Set();
A.values().forEach(item => {
if (!B.has(item)) {
set.add(item);
}
});
return set;
}

只需要遍历集合长度较小的一个即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function differenceSet(A, B) {
const set = new Set();
let smallSet = A;
let bigSet = B;
if (smallSet.values().length > bigSet.values().length) {
smallSet = B;
bigSet = A;
}
smallSet.values().forEach(item => {
if (!bigSet.has(item)) {
set.add(item);
}
});
return set;
}
  • 子集
1
2
3
function childSet(A, B) {
return B.values().every(item => A.has(item))
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2025 SunZhiqi

此时无声胜有声!

支付宝
微信