class MyHashSet: def __init__(self): self.hash = [] def add(self, key: int) -> None: if key not in self.hash: self.hash.append(key) def remove(self, key: int) -> None: if key in self.hash: self.hash.remove(key) def contains(self, key: int) -> bool: if key in self.hash: return True else: return False |
from collections import defaultdict class MyHashSet: def __init__(self): self.mp=defaultdict(int) def add(self, key: int) -> None: self.mp[key]=True def remove(self, key: int) -> None: self.mp[key]=False def contains(self, key: int) -> bool: return self.mp[key] |
感謝狗喵哥提醒,題目有明確表示不能用內建的hash
因此我第一個根本不是hash的定義
第二個是用內建的
hash的定義為:
class MyHashSet: def __init__(self): self.size = 1000 self.hash = [[] for _ in range(self.size)] def __hash__(self, key:int) -> int: return key % self.size def add(self, key: int) -> None: index = self.__hash__(key) if key not in self.hash[index]: self.hash[index].append(key) def remove(self, key: int) -> None: index = self.__hash__(key) if key in self.hash[index]: self.hash[index].remove(key) def contains(self, key: int) -> bool: index = self.__hash__(key) return key in self.hash[index] |