Leetcode 705. 设计哈希集合 - 详解
1.题目核心信息
1.1.题目描述
不使用任何内建的哈希表库设计一个哈希集合(HashSet)。
实现 MyHashSet 类:
void add(key) 向哈希集合中插入值 key 。
bool contains(key) 返回哈希集合中是否存在这个值 key 。
void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
1.2.题目地址
https://leetcode.cn/problems/design-hashset/description/
2.解题方法
2.1.解题思路
链地址法构建哈希集合
3.解题代码
python代码
class Node
():
def __init__(self, val:int = None, next = None):
self.val = val
self.next = next
class MyHashSet
:
# 思路:链地址法
def __init__(self):
self.base = 1006
self.arr = []
for i in range(self.base):
node = Node()
self.arr.append([node, node])
def add(self, key: int) ->
None:
if self.contains(key):
return
val = key % self.base
_, tail = self.arr[val]
tail.next = Node(val = key)
self.arr[val][1] = tail.next
def remove(self, key: int) ->
None:
if not self.contains(key):
return None
val = key % self.base
head, _ = self.arr[val]
while head.next is not None:
if head.next.val == key:
head.next = head.next.next
else:
head = head.next
self.arr[val][1] = head
def contains(self, key: int) ->
bool:
val = key % self.base
head, _ = self.arr[val]
head = head.next
while head is not None:
if head.val == key:
return True
head = head.next
return False
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)