mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-23 16:47:13 +00: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