-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-hashmap.ts
99 lines (84 loc) · 1.95 KB
/
design-hashmap.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class MyHashMap {
size: number = 13;
buckets: Array<HashMapEntry | null>;
constructor() {
this.size = 13;
this.buckets = new Array(this.size).fill(null);
}
put(key: number, value: number): void {
const i: number = this.getIndex(key);
let curr: HashMapEntry | null = this.buckets[i];
if (curr === null) {
this.buckets[i] = new HashMapEntry(key, value);
return;
}
while (curr.next !== null) {
if (curr.key === key) {
curr.value = value;
return;
}
curr = curr.next;
}
if (curr.key === key) {
curr.value = value;
} else {
curr.next = new HashMapEntry(key, value);
}
}
get(key: number): number {
const i: number = this.getIndex(key);
let curr: HashMapEntry | null = this.buckets[i];
if (curr === null) {
return -1;
}
while (curr !== null) {
if (curr.key === key) {
return curr.value;
}
curr = curr.next;
}
return -1;
}
remove(key: number): void {
const i: number = this.getIndex(key);
let curr: HashMapEntry | null = this.buckets[i];
let prev: HashMapEntry | null = null;
if (curr === null) {
return;
}
while (curr != null) {
if (curr.key === key) {
if (prev === null) {
this.buckets[i] = curr.next;
} else {
const next = curr.next;
prev.next = next;
curr.next = null;
}
return;
}
prev = curr;
curr = curr.next;
}
}
getIndex(key: number): number {
return Math.abs((key * 12582917) % this.size);
}
}
class HashMapEntry {
key: number;
value: number;
next: HashMapEntry | null;
constructor(key: number, value: number) {
this.key = key;
this.value = value;
this.next = null;
}
}
/**
* 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)
*/