-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path706. Design HashMap.js
75 lines (66 loc) · 1.3 KB
/
706. Design HashMap.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
68
69
70
71
72
73
74
75
var MyHashMap = function () {
this.base = 769
this.data = new Array(this.base).fill(0).map(() => new Array())
}
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
MyHashMap.prototype.put = function (key, value) {
// 对应数组 index
const ind = this.hash(key)
// 数组拉链
for (const x of this.data[ind]) {
// 查找每一个 tuple
if (x[0] === key) {
// 更新
x[1] = value
return
}
}
// 设置 tuple
this.data[ind].push([key, value])
}
/**
* @param {number} key
* @return {number}
*/
MyHashMap.prototype.get = function (key) {
const ind = this.hash(key)
for (const x of this.data[ind]) {
if (x[0] === key) {
return x[1]
}
}
return -1
}
/**
* @param {number} key
* @return {void}
*/
MyHashMap.prototype.remove = function (key) {
const ind = this.hash(key)
const it = this.data[ind]
for (let i = 0; i < it.length; i++) {
const cur = it[i]
if (cur[0] === key) {
it.splice(i, 1)
return
}
}
}
/**
* @param {number} key
* @return {number}
*/
MyHashMap.prototype.hash = function (key) {
return key % this.base
}
/**
* Your MyHashMap object will be instantiated and called as such:
* var obj = new MyHashMap()
* obj.put(key,value)
* var param_2 = obj.get(key)
* obj.remove(key)
*/