Advertisement
smj007

Untitled

Mar 6th, 2024 (edited)
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. # easier and simpler
  2.  
  3. HASH_NUM = 524287
  4.  
  5. class MyHashSet:
  6.     def __init__(self):
  7.  
  8.         self.tables = [0]*HASH_NUM
  9.        
  10.     def add(self, key: int) -> None:
  11.  
  12.         key = key%HASH_NUM
  13.         self.tables[key] = 1
  14.        
  15.     def remove(self, key: int) -> None:
  16.         key = key%HASH_NUM
  17.         if self.tables[key]:
  18.             self.tables[key] = 0
  19.             return
  20.  
  21.         return
  22.  
  23.     def contains(self, key: int) -> bool:
  24.         key = key%HASH_NUM
  25.         return self.tables[key]  
  26.  
  27.  
  28.  
  29. HASH_NUM = 2069
  30.  
  31. class Node:
  32.     def __init__(self, val):
  33.         self.val = val
  34.         self.next = None
  35.  
  36. class MyHashSet:
  37.  
  38.     def __init__(self):
  39.  
  40.         self.tables = [None]*HASH_NUM
  41.        
  42.     def add(self, key: int) -> None:
  43.  
  44.         # address collision
  45.         if self.tables[key%HASH_NUM]:
  46.             current = self.tables[key%HASH_NUM]
  47.             prev = current
  48.  
  49.             while current:
  50.                 if current.val == key:
  51.                     return
  52.                 prev = current
  53.                 current = current.next
  54.             prev.next = Node(key)
  55.  
  56.         self.tables[key%HASH_NUM] = Node(key)
  57.  
  58.    
  59.     def remove(self, key: int) -> None:
  60.         if self.tables[key%HASH_NUM]:
  61.             current = self.tables[key%HASH_NUM]
  62.             prev = current
  63.  
  64.             # if key matches at the head of the node
  65.             if key == current.val:
  66.                 self.tables[key%HASH_NUM] = current.next
  67.                 return
  68.  
  69.             while current:
  70.                 if key == current.val:
  71.                     prev.next = current.next
  72.                     return
  73.                 prev = current
  74.                 current = current.next
  75.  
  76.  
  77.     def contains(self, key: int) -> bool:
  78.        
  79.         current = self.tables[key%HASH_NUM]
  80.         while current:
  81.             if current.val == key:
  82.                 return True
  83.             current = current.next
  84.        
  85.         return False
  86.  
  87.  
  88. # Your MyHashSet object will be instantiated and called as such:
  89. # obj = MyHashSet()
  90. # obj.add(key)
  91. # obj.remove(key)
  92. # param_3 = obj.contains(key)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement