不使用任何内建的哈希表库设计一个哈希集合
具体地说,你的设计应该包含以下的功能
add(value)
:向哈希集合中插入一个值。contains(value)
:返回哈希集合中是否存在这个值。remove(value)
:将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
示例:
MyHashSet hashSet = new MyHashSet();
hashSet.add(1);
hashSet.add(2);
hashSet.contains(1); // 返回 true
hashSet.contains(3); // 返回 false (未找到)
hashSet.add(2);
hashSet.contains(2); // 返回 true
hashSet.remove(2);
hashSet.contains(2); // 返回 false (已经被删除)
注意:
- 所有的值都在
[1, 1000000]
的范围内。 - 操作的总数目在
[1, 10000]
范围内。 - 不要使用内建的哈希集合库。
思路:
使用JavaScript中的Array来实现,Array中有类似的方法,只需按照需求进行修改即可。
Array方法:
push() 向数组尾添加元素,元素可重复,而需求add(),添加的元素不会重复,因此需要判断是否存在key,没有才能push()
indexOf() 返回数组中某元素的索引,若不存在则返回-1, 对于需求contains(), 返回true/false
splice(index, howmany, item1, item2...itemn) 在index处删除howmany个元素,并添加item1,item2...itemn(item可无)
而需求的remove(),可以使用 splice(index,1)来实现。
/**
* Initialize your data structure here.
*/
var MyHashSet = function() {
this.arr = new Array();
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.add = function(key) {
if (this.arr.indexOf(key) === -1) {
this.arr.push(key);
}
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.remove = function(key) {
if (this.arr.indexOf(key) !== -1) {
this.arr.splice(this.arr.indexOf(key), 1);
}
};
/**
* Returns true if this set did not already contain the specified element
* @param {number} key
* @return {boolean}
*/
MyHashSet.prototype.contains = function(key) {
return this.arr.indexOf(key) !== -1;
};
/**
* Your MyHashSet object will be instantiated and called as such:
* var obj = Object.create(MyHashSet).createNew()
* obj.add(key)
* obj.remove(key)
* var param_3 = obj.contains(key)
*/