

这里是一个使用链地址法(chaining)实现的 MyHashSet,不依赖任何内建的哈希表库:
class MyHashSet:
def __init__(self, capacity=1000):
"""
Initialize the HashSet with a given capacity.
"""
self.capacity = capacity
self.buckets = [[] for _ in range(self.capacity)]
def _hash(self, key):
"""
Compute the hash value of the key.
"""
return key % self.capacity
def add(self, key):
"""
Insert key into the HashSet.
"""
hash_value = self._hash(key)
if key not in self.buckets[hash_value]:
self.buckets[hash_value].append(key)
def contains(self, key):
"""
Return whether the key is in the HashSet.
"""
hash_value = self._hash(key)
return key in self.buckets[hash_value]
def remove(self, key):
"""
Remove key from the HashSet.
"""
hash_value = self._hash(key)
if key in self.buckets[hash_value]:
self.buckets[hash_value].remove(key)
设计思路:
-
哈希函数: 采用简单的取模运算
key % capacity来计算索引,确保键值能够均匀分布在capacity个桶中。 -
桶结构: 采用列表数组
self.buckets来存储数据,每个桶是一个独立的链表(列表)。 -
添加操作 (
add): 计算哈希值并插入到对应的桶中,若该值已存在,则不重复插入。 -
查找操作 (
contains): 计算哈希值,并检查该值是否在对应的桶中。 -
删除操作 (
remove): 计算哈希值并从相应的桶中移除该值。
该实现的平均时间复杂度接近 O(1),在最坏情况下(所有键值冲突)可能达到 O(n)。
1123

被折叠的 条评论
为什么被折叠?



