基础数据结构--手动实现集合及其相关方法

集合(set)是一种包含不同元素的数据结构。每个元素只能存在一次,不能有重复元素出现。
• 不包含任何成员的集合称为空集,全集则是包含一切可能成员的集合。
• 如果两个集合的成员完全相同,则称两个集合相等。
• 如果一个集合中所有的成员都属于另外一个集合,则前一集合称为后一集合的子集。

对集合的几种常见的操作:

• 并集 将两个集合中的成员进行合并,得到一个新集合。
• 交集 两个集合中共同存在的成员组成一个新的集合。
• 补集 属于一个集合而不属于另一个集合的成员组成的集合。

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function Set () {
this.dataStore = []
// 添加
this.add = add
// 删除
this.remove = remove
// 长度
this.size = size
// 展示
this.show = show
// 并集
this.union = union
// 交集
this.intersect = intersect
// 子集
this.subset = subset
// 属于第一个集合但是不属于第二个集合
this.difference = difference
}
function add (data) {
if (this.dataStore.indexOf(data) < 0) {
this.dataStore.push(data)
return true
}
return false
}
function remove (data) {
let pos = this.dataStore.indexOf(data)
if (pos > 0) {
this.dataStore.splice(pos, 1)
return true
}
return false
}
function size () {
return this.dataStore.length
}
function show () {
return this.dataStore
}
function union (set) {
let temp = new Set()
for (let i = 0;i < this.dataStore.length;i++) {
temp.add(this.dataStore[i])
}
for (let i = 0;i < set.dataStore.length;i++) {
if (!temp.contains(set.dataStore[i])) {
temp.dataStore.push(set.dataStore[i])
}
}
return temp
}
function intersect (set) {
let temp = new Set()
for(let i = 0;i < this.dataStore.length;i++) {
if (set.contains(this.dataStore[i])) {
temp.add(this.dataStore[i])
}
}
return temp
}
function subSet (set) {
if (this.size() < set.size()) {
return false
}
for(let key of this.dataStore) {
if (!set.contains(this.dataStore[key])) {
return false
}
}
return true
}
function contains (data) {
return this.dataStore.indexOf(data) > -1
}

注:集合的实现相对比较简单。

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信