Advertisement
smj007

Untitled

Mar 5th, 2024
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. class RandomizedSet:
  2.  
  3.     def __init__(self):
  4.         self.hashmap = {}
  5.         self.list = []
  6.        
  7.  
  8.     def insert(self, val: int) -> bool:
  9.         if val in self.hashmap:
  10.             return False
  11.  
  12.         self.list.append(val)
  13.         self.hashmap[val] = len(self.list) - 1
  14.         return True
  15.            
  16.     def remove(self, val: int) -> bool:
  17.  
  18.         if val not in self.hashmap:
  19.             return False
  20.  
  21.         idx = self.hashmap[val]
  22.         self.list[idx], self.list[-1] = self.list[-1], self.list[idx]
  23.         self.hashmap[self.list[idx]] = idx
  24.  
  25.         self.list.pop()
  26.         del self.hashmap[val]
  27.         return True
  28.        
  29.     def getRandom(self) -> int:
  30.         import random
  31.         return random.choice(self.list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement