forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path706DesignHashMap.js
More file actions
79 lines (72 loc) · 1.56 KB
/
706DesignHashMap.js
File metadata and controls
79 lines (72 loc) · 1.56 KB
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
76
77
78
79
function ListNode(key, value, next = null) {
this.key = key;
this.value = value;
this.next = next;
}
var MyHashMap = function () {
this.SIZE = 10009;
this.buckets = new Array(this.SIZE).fill(null);
};
MyHashMap.prototype.hash = function (key, value) {
return key % this.SIZE;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
MyHashMap.prototype.put = function (key, value) {
const idx = this.hash(key);
if (!this.buckets[idx]) this.buckets[idx] = new ListNode(-1, -1);
let prev = this.buckets[idx];
let curr = prev.next;
while (curr) {
if (curr.key == key) {
curr.value = value;
return;
}
prev = curr;
curr = curr.next;
}
prev.next = new ListNode(key, value);
};
/**
* @param {number} key
* @return {number}
*/
MyHashMap.prototype.get = function (key) {
const idx = this.hash(key);
if (!this.buckets[idx]) return -1;
let prev = this.buckets[idx];
let curr = prev.next;
while (curr) {
if (curr.key == key) return curr.value;
curr = curr.next;
}
return -1;
};
/**
* @param {number} key
* @return {void}
*/
MyHashMap.prototype.remove = function (key) {
const idx = this.hash(key);
if (!this.buckets[idx]) return;
let prev = this.buckets[idx];
let curr = prev.next;
while (curr) {
if (curr.key === key) {
prev.next = curr.next;
return;
}
prev = curr;
curr = curr.next;
}
};
/**
* 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)
*/