class RandomizedSet:
def __init__(self):
self.num_idx_dict = dict()
self.num_list = []
def insert(self, val: int) -> bool:
if val in self.num_idx_dict:
return False
else:
self.num_list.append(val)
self.num_idx_dict[val] = len(self.num_list) - 1
return True
def remove(self, val: int) -> bool:
if val not in self.num_idx_dict:
return False
else:
# 使用replace_val覆盖原先val在list中的位置
remove_idx = self.num_idx_dict[val]
replace_val = self.num_list[-1]
self.num_list[remove_idx] = replace_val
self.num_idx_dict[replace_val] = remove_idx
# dict 删除val,List删除replace_val
self.num_list.pop()
del self.num_idx_dict[val]
return True
def getRandom(self) -> int:
return random.choice(self.num_list)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
04-13
2375
09-25
3266