-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathHashMap.kt
More file actions
44 lines (37 loc) · 1.18 KB
/
HashMap.kt
File metadata and controls
44 lines (37 loc) · 1.18 KB
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
//Time complexity: O(1) on average for put, get, and remove operations
//Space complexity: O(n) where n is the number of unique keys stored in the Hash
import java.util.*
class HashMap() {
private val bucketSize = 10000
private val buckets = Array(bucketSize) { LinkedList<Pair<Int,Int>>() }
fun put(key: Int, value: Int) {
val bucket = key % bucketSize
for ((index, keyValue) in buckets[bucket].withIndex()) {
if (keyValue.first == key) {
buckets[bucket][index] = Pair(key, value)
return
}
}
buckets[bucket].add(Pair(key, value))
}
fun get(key: Int): Int {
val bucket = key % bucketSize
return buckets[bucket].find { it.first == key }?.second ?: -1
}
fun remove(key: Int) {
val bucket = key % bucketSize
for (keyValue in buckets[bucket]) {
if (keyValue.first == key) {
buckets[bucket].remove(keyValue)
break
}
}
}
}
/**
* 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)
*/