还是用的list来解决。
import random
class RandomizedCollection(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.list1 = []
def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.list1:
self.list1.append(val)
return False
else:
self.list1.append(val)
return True
def remove(self, val):
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.list1:
self.list1.remove(val)
return True
else:
return False
def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
return random.choice(self.list1)
不过看到了题目写的是O(1),感觉很多都是O(n)啊,不过不知道怎么才能O(1),倒是也给过了