Do a better RandomizedSet

This commit is contained in:
2023-10-26 03:58:50 -04:00
parent c8a4928ee8
commit c274f59f58
2 changed files with 69 additions and 6 deletions
+34 -2
View File
@@ -396,7 +396,7 @@ def h_index(citations: list[int]) -> int:
return last_qualified or 0
class RandomizedSet:
class SlowRandomizedSet:
def __init__(self):
self._i: set[int] = set()
@@ -412,4 +412,36 @@ class RandomizedSet:
return False
def getRandom(self) -> int:
return next(iter(sorted(list(self._i), key=lambda _: random.random())))
return random.choice(list(self._i))
class RandomizedSet:
def __init__(self):
self._l: list[int] = []
self._m: dict[int, int] = {}
def insert(self, val: int) -> bool:
if val in self._m:
return False
self._m[val] = len(self._l)
self._l.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self._m:
return False
val_loc = self._m[val]
last_val = self._l[-1]
self._l[val_loc] = last_val
self._m[last_val] = val_loc
self._l.pop()
self._m.pop(val)
return True
def getRandom(self) -> int:
return random.choice(self._l)