代码一:在remove中涉及排序操作 时间复杂做不到O(1) 108ms
代码二:继续用空间换时间 字典中存储字典 能做到O(1) 127ms 运行时间还增加了 是没有大的测试数据集吗?
不知道集合删除操作是不是O(1)?望告知
class RandomizedCollection(object):
import random
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict1={}
self.list1=[]
self.index=0
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.dict1:
self.dict1[val].append(self.index)
self.list1.append(val)
self.index+=1
return False
else:
self.dict1[val]=[self.index]
self.list1.append(val)
self.index+=1
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.dict1:
tmp = self.dict1[val].pop()
if self.dict1[val]==[]:
del self.dict1[val]
self.index-=1
p=self.list1[tmp]
q=self.list1[self.index]
if p==q:
self.list1.pop()
else:
self.list1[tmp]=q
self.list1[self.index]=p
self.dict1[q][-1]=tmp
self.dict1[q].sort()
self.list1.pop()
return True
else:
return False
class RandomizedCollection(object):
import random
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict1={}
self.list1=[]
self.index=0
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.dict1:
self.dict1[val][self.index]=True
self.list1.append(val)
self.index+=1
return False
else:
self.dict1[val]={self.index:True}
self.list1.append(val)
self.index+=1
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.dict1:
self.index-=1
if self.index in self.dict1[val]:
del self.dict1[val][self.index]
if len(self.dict1[val])==0:
del self.dict1[val]
self.list1.pop()
else:
tmp = self.dict1[val].popitem()
tmp=tmp[0]
if len(self.dict1[val])==0:
del self.dict1[val]
p=self.list1[tmp]
q=self.list1[self.index]
self.list1[tmp]=q
self.list1[self.index]=p
self.dict1[q][tmp]=True
del self.dict1[q][self.index]
self.list1.pop()
return True
else:
return False
def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
return random.choice(self.list1)