380. O(1) 时间插入、删除和获取随机元素

​​题目来源:

        leetcode题目,网址:380. O(1) 时间插入、删除和获取随机元素

解题思路:

       使用字典存储实现O(1)插入,删除。利用自带的random.choice 实现随机获取。

解题代码:

#python3
class RandomizedSet:
    dic={}
    def __init__(self):
        self.dic={}

    def insert(self, val: int) -> bool:
        if val in self.dic:
            return False
        else:
            self.dic[val]=1
            return True

    def remove(self, val: int) -> bool:
        if val in self.dic:
            self.dic.pop(val)
            return True
        else:
            return False

    def getRandom(self) -> int:
        return random.choice(list(self.dic.keys()))


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
 
  

总结:

        没有想到太好的方法。

        官方题解是使用变长数组+哈希表。使用变长数组存储元素,哈希表存储下标,


你可能感兴趣的:(LeetCode,刷题,LeetCode)