Skip to content

Commit

Permalink
Create 0706-design-hashmap.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored Feb 24, 2023
1 parent fc6ce50 commit 8776fb9
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions kotlin/0706-design-hashmap.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,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)
*/

0 comments on commit 8776fb9

Please sign in to comment.