该模板使用二次探测解决冲突
暂时不支持扩容
一个很好的总结 哈希冲突解决办法的博客
非有序哈希表
重载机制
扩容方法及实例
Hashmap实现原理及扩容机制详解
有时间会写一个 有序+扩容 的哈希表
class HashTable:
def __init__(self, capacity = int(1e5+500)):
self.que = [(None, None, 'unused') for _ in range(capacity)]
self.mod = int(1e5+7)
def _hash(self, key):
hash_num = 0
for i in key:
hash_num = hash_num * 33 + ord(key)
return hash_num % self.mod
def find_pos(self, key):
hash_num = self._hash(key)
ind = 0
while True:
hash_num = (hash_num + ind ** 2) % self.mod
cur = self.que[hash_num]
if cur[2] == 'used' and cur[0] == key:
break
if cur[2] == 'unused':
break
return hash_num
def __contains__(self, key):
pos = self.find_pos(key)
if self.que[pos][2] == 'unused':
return False
else:
return True
def __getitem__(self, key):
pos = self.find_pos(key)
return self.que[pos][1]
def __setitem__(self, key, val):
pos = self.find_pos(key)
self.que[pos] = (key, val, 'used')