Advertisement
smj007

Untitled

Mar 7th, 2024
908
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. class RandomizedCollection:
  2.  
  3.     def __init__(self):
  4.         self.hashmap = defaultdict(set)
  5.         self.list = []
  6.        
  7.     def insert(self, val: int) -> bool:
  8.  
  9.         self.hashmap[val].add(len(self.list))
  10.         self.list.append(val)
  11.         return len(self.hashmap[val]) == 1
  12.        
  13.     def remove(self, val: int) -> bool:
  14.         if self.hashmap[val]:
  15.             indexes = self.hashmap[val]
  16.             index = indexes.pop()
  17.            
  18.             last = self.list[-1]
  19.             self.list[index] = last
  20.  
  21.             self.hashmap[last].add(index)
  22.             self.hashmap[last].remove(len(self.list)-1)
  23.  
  24.             self.list.pop()
  25.             return True
  26.         return False
  27.  
  28.     def getRandom(self) -> int:
  29.         return random.choice(self.list)
  30.        
  31.  
  32.  
  33. # Your RandomizedCollection object will be instantiated and called as such:
  34. # obj = RandomizedCollection()
  35. # param_1 = obj.insert(val)
  36. # param_2 = obj.remove(val)
  37. # param_3 = obj.getRandom()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement