'''
题目要求设计的一个哈希集合
'''
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.buckets = 1001
# 这里用了最简单的求哈希值的方法
# 就是用一个数对一个质数取模,这个质数设置为1001
self.a_list = [[] for _ in range(1000)]
# 哈希表的大小人为设置为1000
def hash(self, key):
# 哈希函数,求哈希值
hashkey = key % self.buckets
return hashkey
def add(self, key: int) -> None:
hashkey = self.hash(key)
if key not in self.a_list[hashkey]:
self.a_list[hashkey].append(key)
return
def remove(self, key: int) -> None:
hashkey = self.hash(key)
if key in self.a_list[hashkey]:
self.a_list[hashkey].remove(key)
return
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
hashkey = self.hash(key)
return key in self.a_list[hashkey]
705. 设计哈希集合 Design HashSet
最新推荐文章于 2021-08-07 14:13:19 发布