a rushed RandomizedSet impl

This commit is contained in:
2023-10-25 20:15:43 -04:00
parent 6d523ad7c1
commit c8a4928ee8
2 changed files with 46 additions and 0 deletions
+20
View File
@@ -1,4 +1,5 @@
import copy
import random
import typing
import stdlib
@@ -393,3 +394,22 @@ def h_index(citations: list[int]) -> int:
break
return last_qualified or 0
class RandomizedSet:
def __init__(self):
self._i: set[int] = set()
def insert(self, val: int) -> bool:
ok = val not in self._i
self._i.add(val)
return ok
def remove(self, val: int) -> bool:
if val in self._i:
self._i.remove(val)
return True
return False
def getRandom(self) -> int:
return next(iter(sorted(list(self._i), key=lambda _: random.random())))