哈希函数
冲突处理
链地址法
开放地址法
再哈希法
扩容
链地址法
1 class ListNode: 2 def __init__(self, val, _next=None): 3 self.val = val 4 self.next = _next 5 6 7 class MyHashSet: 8 9 10 def __init__(self): 11 """ 12 Initialize your data structure here. 13 """ 14 self.base = 1009 15 self.data = [None] * self.base 16 17 18 def __hash(self, key: int): 19 return key % self.base 20 21 22 def add(self, key: int) -> None: 23 head = self.data[self.__hash(key)] 24 25 # 在键对应的空间 存储链表(头节点) 26 if not head: 27 self.data[self.__hash(key)] = ListNode(key) 28 return 29 30 31 # 定位到链表尾部 32 cur = head 33 while cur: 34 prev = cur 35 if cur.val == key: 36 return 37 cur = cur.next 38 39 40 # 插入节点(key) 41 prev.next = ListNode(key) 42 return 43 44 45 def remove(self, key: int) -> None: 46 head = self.data[self.__hash(key)] 47 if not head: 48 return 49 50 51 # 分三种情况讨论 对应空间头节点 头节点的值是否等于key 52 elif head.val == key: 53 self.data[self.__hash(key)] = head.next 54 return 55 56 57 # 节点在链表中 执行定位删除操作 58 cur = head 59 while cur.next: 60 prev = cur 61 cur = cur.next 62 if cur.val == key: 63 prev.next = cur.next 64 return 65 return 66 67 68 def contains(self, key: int) -> bool: 69 """ 70 Returns true if this set contains the specified element 71 """ 72 head = self.data[self.__hash(key)] 73 cur = head 74 # 遍历链表 依次判断 75 while cur: 76 if cur.val == key: 77 return True 78 cur = cur.next 79 80 81 return False
Note:Python中还可以灵活地采用二维链表来模拟
class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.base = 769 self.data = [[]]*self.base def hash(self,key:int) -> int: return key % self.base def add(self, key: int) -> None: hash_key = self.hash(key) if key not in self.data[hash_key]: self.data[hash_key].append(key) def remove(self, key: int) -> None: hash_key = self.hash(key) if key in self.data[hash_key]: self.data[hash_key].remove(key) def contains(self, key: int) -> bool: """ Returns true if this set contains the specified element """ hash_key = self.hash(key) return key in self.data[hash_key]
复杂度分析
Hash表为什么需要使用mod素数?
https://zhuanlan.zhihu.com/p/123261109

浙公网安备 33010602011771号