381. Insert Delete GetRandom O(1) - Duplicates allowed

嗯 这一题还是哈希表,需要注意,不管存不存在都需要进行存储添加,所以主要问题在于remove部分,如果存在字典中,删除后返回true,这时候的做法,首先把同一个value的通过next(iter())取到一个坐标值,把这个坐标上的值和最后一个数字交换,此时字典中可以把这个坐标删除掉,如果这个坐标是最后一位,直接删掉,如果不是,因为把处在最后一位上的数字交换过来了,所以最后一位上的数字现在存在了idx坐标上,因此需要修改这个val的最后一个坐标值,把它变成idx,同时要删除他原来的最后一个坐标值。还需要判断是不是字典中对应的坐标已经被删除完毕了,如果删除完毕了,要把条目也删掉。

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()

你可能感兴趣的:(381. Insert Delete GetRandom O(1) - Duplicates allowed)