-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday55-designhashmap-modulohash.js
61 lines (54 loc) · 1.77 KB
/
day55-designhashmap-modulohash.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
//learning how to use the simplest hashing function
//chaining by linkedlist to handle collisions
let ListNode = function(key, val, next){
this.key = key
this.val = val
this.next = next
}
let MyHashMap = function() {
this.size = 10001
this.hashNum = 345456
this.data = []
this.hash = function (key) {
return key * this.mult % this.size
}
this.put = function (key, val){
//remove existing key first
this.remove(key)
let index = this.hash(key)
//create new node at front of list
let node = new ListNode(key, val, this.data[index])
//set array index to point to new node
this.data[index] = node
}
this.get = function (key){
let index = this.hash(key)
let node = this.data[index]
//loop through linkedlist until key is found
while(node){
if(node.key === key)
return node.val
node = node.next
}
return -1
}
this.remove = function(key){
let index = this.hash(key)
node = this.data[index]
if (!node) return
//if key found, set array index to that node
//javascript will auto clean that memory since it is no longer pointed to
if (node.key === key)
this.data[index] = node.next
else {
while(node){
if (node?.next?.key === key) {
node.next = node.next.next
return
}
node = node.next
}
}
}
};
//https://leetcode.com/problems/design-hashmap