-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDesign HashMap.js
More file actions
50 lines (40 loc) · 1018 Bytes
/
Design HashMap.js
File metadata and controls
50 lines (40 loc) · 1018 Bytes
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
class MyHashMap {
constructor() {
this.size = 1000;
this.buckets = Array.from({ length: this.size }, () => []);
}
hash(key) {
return key % this.size;
}
put(key, value) {
let index = this.hash(key);
let bucket = this.buckets[index];
for (let pair of bucket) {
if (pair[0] === key) {
pair[1] = value;
return;
}
}
bucket.push([key, value]);
}
get(key) {
let index = this.hash(key);
let bucket = this.buckets[index];
for (let pair of bucket) {
if (pair[0] === key) {
return pair[1];
}
}
return -1;
}
remove(key) {
let index = this.hash(key);
let bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
if (bucket[i][0] === key) {
bucket.splice(i, 1);
return;
}
}
}
}