O(1)的复杂度 很显然要用字典
随机取值 利用random
class RandomizedSet(object):
import random
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict1={}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.dict1:
return False
else:
self.dict1[val]=True
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.dict1:
del self.dict1[val]
return True
else:
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.sample(self.dict1.keys(),1)[0]