Add the codes of hashmap (#553)

of chaining and open addressing
This commit is contained in:
Yudong Jin
2023-06-14 02:01:06 +08:00
committed by GitHub
parent d3e597af94
commit 9563965a20
27 changed files with 1280 additions and 207 deletions

View File

@ -5,8 +5,8 @@ Author: msk397 (machangxinq@gmail.com)
"""
class Entry:
"""键值对 int->String"""
class Pair:
"""键值对"""
def __init__(self, key: int, val: str):
self.key = key
@ -19,7 +19,7 @@ class ArrayHashMap:
def __init__(self):
"""构造方法"""
# 初始化数组,包含 100 个桶
self.buckets: list[Entry | None] = [None] * 100
self.buckets: list[Pair | None] = [None] * 100
def hash_func(self, key: int) -> int:
"""哈希函数"""
@ -29,26 +29,26 @@ class ArrayHashMap:
def get(self, key: int) -> str:
"""查询操作"""
index: int = self.hash_func(key)
pair: Entry = self.buckets[index]
pair: Pair = self.buckets[index]
if pair is None:
return None
return pair.val
def put(self, key: int, val: str) -> None:
def put(self, key: int, val: str):
"""添加操作"""
pair = Entry(key, val)
pair = Pair(key, val)
index: int = self.hash_func(key)
self.buckets[index] = pair
def remove(self, key: int) -> None:
def remove(self, key: int):
"""删除操作"""
index: int = self.hash_func(key)
# 置为 None ,代表删除
self.buckets[index] = None
def entry_set(self) -> list[Entry]:
def entry_set(self) -> list[Pair]:
"""获取所有键值对"""
result: list[Entry] = []
result: list[Pair] = []
for pair in self.buckets:
if pair is not None:
result.append(pair)
@ -70,7 +70,7 @@ class ArrayHashMap:
result.append(pair.val)
return result
def print(self) -> None:
def print(self):
"""打印哈希表"""
for pair in self.buckets:
if pair is not None: