数据结构与算法的JavaScript描述——集合
说明:以下部分均为《数据结构与算法的JavaScript描述》学习内容及笔记。
1、集合的特性
- 集合成员是无序的。
- 集合中不允许相同的成员存在。
2、Set类的实现
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;
}
2.1 add() 添加
function add(data){
if(this.dataStore.indexOf(data)<0){
this.dataStore.push(data);
return true;
}else{
return false;
}
}
2.2 remove() 删除
function remove(data){
var pos=this.dataStore.indexOf(data);
if(pos>-1){
this.dataStore.splice(pos,1);
return true;
}else{
return false;
}
}
2.3 show() 显示
function show(){
return this.dataStore;
}
2.4 union() 并集操作
//成员是否存在
function contains(data){
if(this.dataStore.indexOf(data)>-1){
return true;
}else{
return false;
}
}
function union(set){
var tempSet=nwe Set();
for(var i=0;i<this.dataStore.length;i++){
tempSet.add(this.dataStore[i]);
}
for(var i=0;i<set.dataStore.length;i++){
if(!tempSet.contains(set.dataStore[i])){
tempSet.dataStore.push(set.dataStore[i]);
}
}
return tempSet;
}
2.5 intersect() 求两个集合的交集
function intersect(set){
var tempSet=new Set();
for(var i=0;i<this.dataStore.length;i++){
if(set.contains(this.dataStore[i])){
tempSet.add(this.dataStore[i]);
}
}
return tempSet;
}
2.6 subset() 是否为子集
function subset(set){
if(this.size()>set.size()){
return false;
}else{
for(var menber in this.dataStore){
if(!set.contains(menber)){
return false;
}
}
}
return true;
}
2.7 difference() 补集
function difference(set){
var tempSet=new Set();
for(var i=0;i<this.dataStore.length;i++){
if(!set.contains(this.dataStore[i]){
tempSet.add(dataStore[i]);
}
}
return tempSet;
}