This commit is contained in:
krahets
2024-03-21 04:22:07 +08:00
parent 35a07170c0
commit cfdb743939
52 changed files with 292 additions and 290 deletions

View File

@ -618,7 +618,7 @@ comments: true
/* 负载因子 */
func loadFactor() -> Double {
Double(size / capacity)
Double(size) / Double(capacity)
}
/* 查询操作 */
@ -664,9 +664,10 @@ comments: true
for (pairIndex, pair) in bucket.enumerated() {
if pair.key == key {
buckets[index].remove(at: pairIndex)
size -= 1
break
}
}
size -= 1
}
/* 扩容哈希表 */
@ -2004,7 +2005,7 @@ comments: true
/* 负载因子 */
func loadFactor() -> Double {
Double(size / capacity)
Double(size) / Double(capacity)
}
/* 搜索 key 对应的桶索引 */

View File

@ -983,13 +983,11 @@ index = hash(key) % capacity
/* 基于数组实现的哈希表 */
class ArrayHashMap {
private var buckets: [Pair?] = []
private var buckets: [Pair?]
init() {
// 初始化数组,包含 100 个桶
for _ in 0 ..< 100 {
buckets.append(nil)
}
buckets = Array(repeating: nil, count: 100)
}
/* 哈希函数 */
@ -1021,35 +1019,17 @@ index = hash(key) % capacity
/* 获取所有键值对 */
func pairSet() -> [Pair] {
var pairSet: [Pair] = []
for pair in buckets {
if let pair = pair {
pairSet.append(pair)
}
}
return pairSet
buckets.compactMap { $0 }
}
/* 获取所有键 */
func keySet() -> [Int] {
var keySet: [Int] = []
for pair in buckets {
if let pair = pair {
keySet.append(pair.key)
}
}
return keySet
buckets.compactMap { $0?.key }
}
/* 获取所有值 */
func valueSet() -> [String] {
var valueSet: [String] = []
for pair in buckets {
if let pair = pair {
valueSet.append(pair.val)
}
}
return valueSet
buckets.compactMap { $0?.val }
}
/* 打印哈希表 */