forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement-hash-map-using-linkedlist.ts
More file actions
85 lines (69 loc) · 1.73 KB
/
implement-hash-map-using-linkedlist.ts
File metadata and controls
85 lines (69 loc) · 1.73 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
80
81
82
83
84
85
// Time Complexity, Amortized - O(1), worst case - O(n), where n is number of inserted elements
// Space Complexity: O(n), where n is number of inserted elements
class MyHashMap {
private storage: Node[];
private buckets: number;
constructor() {
this.buckets = 1000;
this.storage = new Array(this.buckets);
}
getHash(key: number): number {
return key % this.buckets;
}
helper(head: Node, key: number): Node {
let prev = head;
let curr = head.next;
while (curr !== null && curr.key !== key) {
prev = curr;
curr = curr.next;
}
return prev;
}
put(key: number, value: number): void {
const bucket = this.getHash(key);
if (!this.storage[bucket]) {
const newNode = new Node(-1, -1);
this.storage[bucket] = newNode;
}
// get previous node
let prev = this.helper(this.storage[bucket], key);
// update the value if key already exists
if (prev.next !== null) {
prev.next.value = value;
} else {
// append a new node
prev.next = new Node(key, value);
}
}
get(key: number): number {
const bucket = this.getHash(key);
if (!this.storage[bucket]) return -1;
let prev = this.helper(this.storage[bucket], key);
// return the value if key already exists
if (prev.next !== null) {
return prev.next.value;
} else {
return -1;
}
}
remove(key: number): void {
const bucket = this.getHash(key);
if (!this.storage[bucket]) return;
let prev = this.helper(this.storage[bucket], key);
if (prev.next !== null) {
let curr = prev.next;
prev.next = curr.next;
curr.next = null;
}
}
}
class Node {
public key: number;
public value: number;
public next: Node | null;
constructor(key: number, value: number) {
this.key = key;
this.value = value;
this.next = null;
}
}