您的位置:首页 > 理论基础 > 数据结构算法

学习Javascript数据结构与算法系列笔记(三):集合

2017-09-30 11:18 351 查看
集合是一个既没有重复元素,也没有顺序概念的数组。

集合操作:并集、交集、差集等。

创建集合

利用对象来实现集合(items): 对象不允许一个键指向2个不同的属性,保证集合里元素的唯一性。

集合可用方法:

❀ add(value): 向集合添加一个新的项。

❀ remove(value): 移除一个值

❀ has(value): 是否有value值

❀ clear(): 清空集合

❀ size(): 返回集合数量

❀ values(): 返回一个包含集合中所有值的数组

has(value) 方法

this.has = function(value) {
return value in items;
}


使用 in 验证是否为 items 对象的属性。 but
hasOwnProperty
方法会更实用。。

this.has = function(value) {
return items.hasOwnProperty(value);
}


add(value) 方法

判断是否在集合里,有就添加,没有返回false。

this.add = function(value) {
if (!this.has(value)) {
items[value] = value;
return true;
}
return false;
}


remove 和 clear 方法

判断是否在集合里,有就delete,没有返回false。

this.remove = function(value) {
if (!this.has(value)) {
delete items[value];
return true;
}
return false;
}

this.clear = function() {
items = {};
}


size 方法

使用 Object 类的 Keys 方法, 返回一个包含给定对象所有属性的数组。

this.size = function() {
return Obejct.keys(items).length;
}


values 方法

Object.keys(object);

this.values = function() {
return Obejct.keys(items);
}


传统方法

this.valuesLegacy = function() {
var keys = [];
for(var key in items) {
keys.push(key);
}
return keys;
}


使用 Set 类

var Set = function() {
var items = {};
...
}
var set = new Set();
set.add(1);
console.log(set.values);//=>["1"]
console.log(set.has(1));//=>true
console.log(set.size());//=>1

set.add(2);
console.log(set.values);//=>["1","2"]
console.log(set.has(2));//=>true
console.log(set.size());//=>2

set.remove(1);
console.log(set.values);//=>["2"]

set.remove(2);
console.log(set.values);//=>[]


集合操作

集合操作:

❀ 并集: 2个集合,返回包含2个集合的所有元素集合

❀ 交集: 2个集合,返回2个集合都有元素集合

❀ 差集: 2个集合,返回第一个集合有第二个集合没有的元素集合

❀ 子集: 验证一个给定集合是否是另一个集合的子集

并集 union 方法

this.union = function(otherSet) {
var unionSet = new Set(); //创建一个新集合
var values = this.values();//获取第一个集合的所有值,塞到并集的集合中
for(var i=0; i < values.length; i++){
unionSet.add(values[i]);
}
values = otherSet.values; //同上获取给定的第二个集合
for(var i=0; i < values.length; i++){
unionSet.add(values[i]);
}
return unionSet;
}


交集 intersection 方法

this.intersection = function(otherSet) {
var intersectionSet = new Set();
var values = this.values();
for(var i=0; i < values.length; i++) {
if(otherSet.has(values[i])) {
intersectionSet.add(values[i]);
}
}
return intersectionSet;
}


差集 difference 方法

this.difference = function(otherSet) {
var differenceSet = new Set();
var values = this.values();
for(var i=0; i < values.length; i++) {
if(!otherSet.has(values[i])) {
differenceSet.add(values[i]);
}
}
return differenceSet;
}


子集 subset 方法

this.subset = function(otherSet) {
if(this.size() > otherSet.size()) {
return false;
} else {
var values = this.values();
for(var i=0; i < values.length; i++) {
if(!otherSet.has(values[i])) {
return false;
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息