还是用的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),倒是也给过了
本文介绍了一个使用Python列表实现的随机集合类,该类支持插入、删除元素及获取随机元素的功能。虽然作者指出了一些操作的时间复杂度可能为O(n),但整体上提供了一种简单的方法来实现这些功能。
819

被折叠的 条评论
为什么被折叠?



