前言
省略
代码
kotlin
class MyHashMap {
data class Node(
var key: Int, var value: Int, var next: Node? = null
)
// 负载因子
private var loadFactor = 0.75
// 当前大小
private var size = 0
private var table = Array<Node?>(16) {
null
}
// 增加
fun put(key: Int, value: Int) {
// hash确定下标
val n = key.hashCode() % table.size
if (table[n] == null) {
table[n] = Node(key, value)
} else {
// 找到最后一个
var e = table[n]
while (e != null) {
// 替换
if (e.key == key) {
e.value = value
break
}
if (e.next == null) {
e.next = Node(key, value)
break
}
e = e.next
}
}
// 扩容
if (++size > table.size * loadFactor) {
resize()
}
}
// 删除
fun remove(key: Int): Node? {
return null
}
// 查
fun get(key: Int): Node? {
return null
}
// 二倍扩容
private fun resize() {
// 数组扩容到2倍
val oldCap = table.size
val newCap = table.size * 2
val newTable = Array<Node?>(newCap) {
table.getOrNull(it)
}
table = newTable
// 转移
for (i in 0 until oldCap) {
var lowHead: Node? = null
var lowTail: Node? = null
var highHead: Node? = null
var highTail: Node? = null
var e = table[i]
while (e != null) {
if (e.key and table.size == 0) {
if (lowHead == null) {
lowHead = e
} else {
lowTail?.next = e
}
lowTail = e
} else {
if (highHead == null) {
highHead = e
} else {
highTail?.next = e
}
highTail = e
}
e = e.next
}
lowTail?.next = null
highTail?.next = null
table[i] = lowHead
table[table.size / 2 + i] = lowTail
}
}
fun size() = size
}
总结
以后写
后续
代码没写完,后面补上