持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第29天,点击查看活动详情
一、题目描述:
不使用任何内建的哈希表库设计一个哈希集合(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 <= 10^6
- 最多调用 10^4 次 add、remove 和 contains
二、思路分析:
由于给定了范围,所以可以用数组作为哈希表结构,要表示集合,就要表示某一元素存在或者不存在于该集合,所以对应索引处取True或者False即可达到此功能,于是便可以设计出相应的add、remove、contains函数
三、AC 代码:
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashset = [False] * (10**6+1)
def add(self, key: int) -> None:
self.hashset[key] = True
def remove(self, key: int) -> None:
self.hashset[key] = False
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
return self.hashset[key]
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
范文参考:
Java + 位运算,高空间效率+高时间效率的解法!!! - 设计哈希集合 - 力扣(LeetCode)