Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # easier and simpler
- HASH_NUM = 524287
- class MyHashSet:
- def __init__(self):
- self.tables = [0]*HASH_NUM
- def add(self, key: int) -> None:
- key = key%HASH_NUM
- self.tables[key] = 1
- def remove(self, key: int) -> None:
- key = key%HASH_NUM
- if self.tables[key]:
- self.tables[key] = 0
- return
- return
- def contains(self, key: int) -> bool:
- key = key%HASH_NUM
- return self.tables[key]
- HASH_NUM = 2069
- class Node:
- def __init__(self, val):
- self.val = val
- self.next = None
- class MyHashSet:
- def __init__(self):
- self.tables = [None]*HASH_NUM
- def add(self, key: int) -> None:
- # address collision
- if self.tables[key%HASH_NUM]:
- current = self.tables[key%HASH_NUM]
- prev = current
- while current:
- if current.val == key:
- return
- prev = current
- current = current.next
- prev.next = Node(key)
- self.tables[key%HASH_NUM] = Node(key)
- def remove(self, key: int) -> None:
- if self.tables[key%HASH_NUM]:
- current = self.tables[key%HASH_NUM]
- prev = current
- # if key matches at the head of the node
- if key == current.val:
- self.tables[key%HASH_NUM] = current.next
- return
- while current:
- if key == current.val:
- prev.next = current.next
- return
- prev = current
- current = current.next
- def contains(self, key: int) -> bool:
- current = self.tables[key%HASH_NUM]
- while current:
- if current.val == key:
- return True
- current = current.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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement