嗯 這一題還是哈希表间学,需要注意,不管存不存在都需要進行存儲添加追驴,所以主要問題在于remove部分,如果存在字典中疏之,刪除后返回true殿雪,這時候的做法,首先把同一個value的通過next(iter())取到一個坐標(biāo)值锋爪,把這個坐標(biāo)上的值和最后一個數(shù)字交換丙曙,此時字典中可以把這個坐標(biāo)刪除掉,如果這個坐標(biāo)是最后一位其骄,直接刪掉亏镰,如果不是,因為把處在最后一位上的數(shù)字交換過來了拯爽,所以最后一位上的數(shù)字現(xiàn)在存在了idx坐標(biāo)上索抓,因此需要修改這個val的最后一個坐標(biāo)值,把它變成idx,同時要刪除他原來的最后一個坐標(biāo)值纸兔。還需要判斷是不是字典中對應(yīng)的坐標(biāo)已經(jīng)被刪除完畢了惰瓜,如果刪除完畢了,要把條目也刪掉汉矿。
import collections
from random import randint
class RandomizedCollection(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.lists = []
self.zd = collections.defaultdict(set)
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.zd:
flag = False
else:
flag = True
self.lists.append(val)
self.zd[val].add(len(self.lists)-1)
return flag
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.zd:
idx = next(iter(self.zd[val]))
self.lists[idx], self.lists[len(self.lists)-1] = self.lists[len(self.lists)-1], self.lists[idx]
self.zd[val].remove(idx)
if idx < len(self.lists) - 1:
self.zd[self.lists[idx]].remove(len(self.lists)-1)
self.zd[self.lists[idx]].add(idx)
self.lists.pop()
if len(self.zd[val]) == 0:
del self.zd[val]
return True
else:
return False
def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
rdx = randint( 0, len(self.lists)-1)
return self.lists[rdx]
# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()