数据结构篇——集合

集合中的元素被称为成员,这种数据结构有两个特点:

  • 集合内的成员是无序的
  • 集合内的成员不可重复

在这里我们用数组来实现集合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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
function Set() {
this.dataStore = []
this.add = add
this.remove = remove
this.size = size
this.union = union
this.intersect = intersect
this.subset = subset
this.difference = difference
this.show = show
}

function add(data){
if(this.dataStore.indexOf(data) < 0){
this.dataStore.push(data)
return true
}else {
return false
}
}

function remove(data){
let pos = this.dataStore.indexOf(data)
if(pos > -1) {
this.dataStore.splice(pos, 1)
return true
}else {
return false
}
}

// 判断一个元素是否在集合中
function contains(data){
if(this.dataStore.indexOf(data)>-1){
return true
}else {
return false
}
}

// 合并两个集合
function union(set){
let tempSet = new Set()
for(let i = o; i < this.dataStore.length; i++){
tempSet.add(this.dataStore[i])
}
for(let i = 0; i < set.dataStore.length; ++i){
if(!tempSet.contains(set.dataStore[i])){
tempSet.add(set.dataStore[i])
}
}
return tempSet
}

// 返回两个集合的交集
function intersect(set){
let tempSet = new Set()
for(let i = 0; i < this.dataStore.length; i++){
if(set.contains(this.dataStore[i])){
tempSet.add(this.dataStore[i])
}
}
return tempSet
}

// 返回集合的长度
function size(){
return this.dataStore.length
}

// 判断一个集合是否是另一个集合的子集
function subset(set){
if(this.size() > set.size()){
return false
}else {
for(let i of this.dataStore){
if(!set.contains(i)){
return false
}
}
}
return true
}

// 返回两个集合的补集
function difference(set){
let tempSet = new Set()
for(let i = 0; i < this.dataStore.length; i++){
if(!set.contains(this.dataStore[i])){
tempSet.add(this.dataStore[i])
}
}
return tempSet
}