题目地址(705. 设计哈希集合)
https://leetcode.cn/problems/design-hashset/
题目描述
不使用任何内建的哈希表库设计一个哈希集合(HashSet)。
实现 MyHashSet 类:
void add(key) 向哈希集合中插入值 key 。
bool contains(key) 返回哈希集合中是否存在这个值 key 。
void remove(key) 将给定值 key 从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
示例:
输入:
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
输出:
[null, null, null, true, false, null, true, null, false]
解释:
MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // 返回 True
myHashSet.contains(3); // 返回 False ,(未找到)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // 返回 True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // 返回 False ,(已移除)
提示:
0 <= key <= 106
最多调用 104 次 add、remove 和 contains
前置知识
公司
- 暂无
思路
关键点
代码
- 语言支持:Python3
Python3 Code:
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
class MyHashSet:
def __init__(self):
# 需要实现哈希表的增删查
self.capacity = 769
self.A = [Node(-1) for _ in range(self.capacity)]
def add(self, key: int) -> None:
i = key % self.capacity
if not self.contains(key):
new_node = Node(key)
head = self.A[i]
new_node.next = head.next
head.next = new_node
def remove(self, key: int) -> None:
i = key % self.capacity
cur = self.A[i].next
pre = self.A[i]
while cur:
if cur.val == key:
pre.next = cur.next
cur = cur.next
pre = pre.next
def contains(self, key: int) -> bool:
i = key % self.capacity
cur = self.A[i].next
while cur:
if cur.val == key:
return True
cur = cur.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)
复杂度分析
令 n 为数组长度。
- 时间复杂度: O ( 1 ) O(1) O(1)
- 空间复杂度: O ( n ) O(n) O(n)