Skip to content

Commit 8776fb9

Browse files
authored
Create 0706-design-hashmap.kt
1 parent fc6ce50 commit 8776fb9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Diff for: kotlin/0706-design-hashmap.kt

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class ChainNode(
2+
var key: Int = -1,
3+
var value: Int = -1
4+
) {
5+
var next: ChainNode? = null
6+
}
7+
8+
class MyHashMap() {
9+
10+
val hashMap = Array(1000) { ChainNode() }
11+
12+
fun put(key: Int, value: Int) {
13+
var current: ChainNode? = hashMap[key % hashMap.size]
14+
while(current?.next != null) {
15+
if(current.next?.key == key) {
16+
current.next?.value = value
17+
return
18+
}
19+
current = current?.next
20+
}
21+
current?.next = ChainNode(key, value)
22+
}
23+
24+
fun get(key: Int): Int {
25+
var current: ChainNode? = hashMap[key % hashMap.size].next
26+
while(current != null) {
27+
if(current.key == key) return current.value
28+
current = current.next
29+
}
30+
return -1
31+
}
32+
33+
fun remove(key: Int) {
34+
var current: ChainNode? = hashMap[key % hashMap.size]
35+
while(current != null && current.next != null) {
36+
if(current.next?.key == key) {
37+
current.next = current.next?.next
38+
return
39+
}
40+
current = current.next
41+
}
42+
}
43+
}
44+
45+
/**
46+
* Your MyHashMap object will be instantiated and called as such:
47+
* var obj = MyHashMap()
48+
* obj.put(key,value)
49+
* var param_2 = obj.get(key)
50+
* obj.remove(key)
51+
*/

0 commit comments

Comments
 (0)