-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
67 lines (63 loc) · 1.36 KB
/
solution.js
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
/**
* Initialize your data structure here.
*/
// 除留余数法
var MyHashSet = function () {
this.list = new Array(512);
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.add = function (key) {
const hash = key % 503;
const list = this.list[hash] || (this.list[hash] = []);
for (let i = 0; i < list.length; i++) {
if (list[i] === key) {
return;
}
}
list.push(key);
};
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.remove = function (key) {
const hash = key % 503;
const list = this.list[hash];
if (!list) {
return;
}
for (let i = 0; i < list.length; i++) {
if (list[i] === key) {
list.splice(i, 1);
return;
}
}
};
/**
* Returns true if this set contains the specified element
* @param {number} key
* @return {boolean}
*/
MyHashSet.prototype.contains = function (key) {
const hash = key % 503;
const list = this.list[hash];
if (!list) {
return false;
}
for (let i = 0; i < list.length; i++) {
if (list[i] === key) {
return true;
}
}
return false;
};
/**
* 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)
*/