mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-07 19:46:29 +08:00
build
This commit is contained in:
@@ -571,7 +571,7 @@ comments: true
|
||||
输入一个 `key` ,哈希函数的计算过程分为以下两步。
|
||||
|
||||
1. 通过某种哈希算法 `hash()` 计算得到哈希值。
|
||||
2. 将哈希值对桶数量(数组长度)`capacity` 取模,从而获取该 `key` 对应的数组索引 `index` 。
|
||||
2. 将哈希值对桶数量(数组长度)`capacity` 取模,从而获取该 `key` 对应的桶(数组索引)`index` 。
|
||||
|
||||
```shell
|
||||
index = hash(key) % capacity
|
||||
@@ -610,7 +610,7 @@ index = hash(key) % capacity
|
||||
index = key % 100
|
||||
return index
|
||||
|
||||
def get(self, key: int) -> str:
|
||||
def get(self, key: int) -> str | None:
|
||||
"""查询操作"""
|
||||
index: int = self.hash_func(key)
|
||||
pair: Pair = self.buckets[index]
|
||||
@@ -619,7 +619,7 @@ index = hash(key) % capacity
|
||||
return pair.val
|
||||
|
||||
def put(self, key: int, val: str):
|
||||
"""添加操作"""
|
||||
"""添加和更新操作"""
|
||||
pair = Pair(key, val)
|
||||
index: int = self.hash_func(key)
|
||||
self.buckets[index] = pair
|
||||
|
||||
@@ -49,3 +49,7 @@ comments: true
|
||||
**Q**:为什么哈希表扩容能够缓解哈希冲突?
|
||||
|
||||
哈希函数的最后一步往往是对数组长度 $n$ 取模(取余),让输出值落在数组索引范围内;在扩容后,数组长度 $n$ 发生变化,而 `key` 对应的索引也可能发生变化。原先落在同一个桶的多个 `key` ,在扩容后可能会被分配到多个桶中,从而实现哈希冲突的缓解。
|
||||
|
||||
**Q**:如果为了高效的存取,那么直接使用数组不就好了吗?
|
||||
|
||||
当数据的 `key` 是连续的小范围整数时,直接用数组即可,简单高效。但当 `key` 是其他类型(例如字符串)时,就需要借助哈希函数将 `key` 映射为数组索引,再通过桶数组存储元素,这样的结构就是哈希表。
|
||||
|
||||
Reference in New Issue
Block a user