forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0706-design-hashmap.kt
51 lines (45 loc) · 1.26 KB
/
0706-design-hashmap.kt
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
class ChainNode(
var key: Int = -1,
var value: Int = -1
) {
var next: ChainNode? = null
}
class MyHashMap() {
val hashMap = Array(1000) { ChainNode() }
fun put(key: Int, value: Int) {
var current: ChainNode? = hashMap[key % hashMap.size]
while(current?.next != null) {
if(current.next?.key == key) {
current.next?.value = value
return
}
current = current?.next
}
current?.next = ChainNode(key, value)
}
fun get(key: Int): Int {
var current: ChainNode? = hashMap[key % hashMap.size].next
while(current != null) {
if(current.key == key) return current.value
current = current.next
}
return -1
}
fun remove(key: Int) {
var current: ChainNode? = hashMap[key % hashMap.size]
while(current != null && current.next != null) {
if(current.next?.key == key) {
current.next = current.next?.next
return
}
current = current.next
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* var obj = MyHashMap()
* obj.put(key,value)
* var param_2 = obj.get(key)
* obj.remove(key)
*/