-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path705. Design HashSet.js
58 lines (52 loc) · 1.05 KB
/
705. Design HashSet.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
var MyHashSet = function () {
this.base = 769
this.data = new Array(this.base).fill(0).map(() => new Array())
}
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.add = function (key) {
if (this.contains(key)) return
const ind = this.hash(key)
this.data[ind].push(key)
}
/**
* @param {number} key
* @return {void}
*/
MyHashSet.prototype.remove = function (key) {
const h = this.hash(key)
const it = this.data[h]
for (let i = 0; i < it.length; ++i) {
if (it[i] === key) {
it.splice(i, 1)
return
}
}
}
/**
* @param {number} key
* @return {boolean}
*/
MyHashSet.prototype.contains = function (key) {
const ind = this.hash(key)
for (const x of this.data[ind]) {
if (x === key) return true
}
return false
}
/**
* @param {number} key
* @return {number}
*/
MyHashSet.prototype.hash = function (key) {
return key % this.base
}
/**
* Your MyHashSet object will be instantiated and called as such:
* var obj = new MyHashSet()
* obj.add(key)
* obj.remove(key)
* var param_3 = obj.contains(key)
*/