集合的实现2--使用数组

本文介绍了一种使用数组来模拟集合的方法,并提供了相应的JavaScript代码实现。文中定义了一个Set类,支持add、has、remove等基本操作,同时实现了union、intersection等集合运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上节我们使用了对象来实现集合类,这节我们使用数组来实现同样的功能

/*
	使用数组来模拟集合
*/
function Set() {
	var items = [];

	this.add = function (value) {
		if(this.has(value)) {
			return false;
		}

		items.push(value);
		return true;
	}

	this.has = function (value) {
		if(items.indexOf(value) == -1) {
			return false;
		}

		return true;
	}

	this.remove = function (value) {
		if(this.has(value)) {
			var index = items.indexOf(value);
			items.splice(index, 1);
			return true;
		}

		return false;
	}

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

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

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

	this.print = function () {
		console.log(items);
	}

	this.union = function (other_set) {
		var new_set = new Set();
		var values = this.values();
		for(var i=0; i<values.length; ++i) {
			new_set.add(values[i]);
		}

		values = other_set.values();
		for(var i=0; i<values.length; ++i) {
			if(!new_set.has(values[i])) {
				new_set.add(values[i]);
			}
		}

		return new_set;
	}

	this.intersection = function (other_set) {
		var new_set = new Set();
		var values = this.values();

		for(var i=0; i<values.length; ++i) {
			if(other_set.has(values[i])) {
				new_set.add(values[i]);
			}
		}

		return new_set;
	}

	this.difference = function (other_set) {
		var new_set = new Set();
		var values = this.values();

		for(var i=0; i<values.length; ++i) {
			if(!other_set.has(values[i])) {
				new_set.add(values[i]);
			}
		}

		return new_set;
	}

	this.isSubset = function (other_set) {
		var flag = true;
		var values = other_set.values();
		for(var i=0; i<values.length; ++i) {
			if(!this.has(values[i])) {
				return false;
			}
		}

		return true;
	}
}

function getSet(arr) {
	var set = new Set();
	for(var i=0; i<arr.length; ++i) {
		set.add(arr[i]);
	}

	return set;
}

var arr1 = [1, 1, 2, 2, 3, 2, 4]  
var set1 = getSet(arr1); // set : [1, 2, 3, 4];

var arr2 = [1, 4, 5, 4, 4, 6];
var set2 = getSet(arr2);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值