This commit is contained in:
krahets
2024-04-13 21:17:44 +08:00
parent 9332a91e26
commit 6afa70e7bc
55 changed files with 334 additions and 182 deletions
@@ -560,6 +560,7 @@ The design of hash algorithms is a complex issue that requires consideration of
/* 加法哈希 */
fun addHash(key: String): Int {
var hash = 0L
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = (hash + c.code) % MODULUS
}
@@ -569,6 +570,7 @@ The design of hash algorithms is a complex issue that requires consideration of
/* 乘法哈希 */
fun mulHash(key: String): Int {
var hash = 0L
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = (31 * hash + c.code) % MODULUS
}
@@ -578,6 +580,7 @@ The design of hash algorithms is a complex issue that requires consideration of
/* 异或哈希 */
fun xorHash(key: String): Int {
var hash = 0
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = hash xor c.code
}
@@ -587,6 +590,7 @@ The design of hash algorithms is a complex issue that requires consideration of
/* 旋转哈希 */
fun rotHash(key: String): Int {
var hash = 0L
val MODULUS = 1000000007
for (c in key.toCharArray()) {
hash = ((hash shl 4) xor (hash shr 28) xor c.code.toLong()) % MODULUS
}
+1 -1
View File
@@ -1312,7 +1312,7 @@ The code below provides a simple implementation of a separate chaining hash tabl
```kotlin title="hash_map_chaining.kt"
/* 链式地址哈希表 */
class HashMapChaining() {
class HashMapChaining {
var size: Int // 键值对数量
var capacity: Int // 哈希表容量
val loadThres: Double // 触发扩容的负载因子阈值
+3 -2
View File
@@ -1605,7 +1605,8 @@ The following code implements a simple hash table. Here, we encapsulate `key` an
fun valueSet(): MutableList<String> {
val valueSet = mutableListOf<String>()
for (pair in buckets) {
pair?.let { valueSet.add(it._val) }
if (pair != null)
valueSet.add(pair._val)
}
return valueSet
}
@@ -1615,7 +1616,7 @@ The following code implements a simple hash table. Here, we encapsulate `key` an
for (kv in pairSet()) {
val key = kv.key
val _val = kv._val
println("${key} -> ${_val}")
println("$key -> $_val")
}
}
}