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

这道题需要注意:
1、O(1) 的查询肯定是hash表
2、删除数组时,删除最后一个快,否则删除中间导致后面的需要前移
3、random.choice():Choose a random element from a non-empty sequence.

class RandomizedSet:
    def __init__(self):
        self.vals = []
        self.indexs = {}

    def insert(self, val: int) -> bool:
        if val in self.indexs:
            return False
        self.indexs[val] = len(self.vals)
        self.vals.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.indexs:
            return False
        index = self.indexs[val]
        self.vals[index] = self.vals[-1]
        self.indexs[self.vals[index]] = index
        self.vals.pop()
        del self.indexs[val]
        return True

    def getRandom(self) -> int:
        return random.choice(self.vals)

你可能感兴趣的:(LeetCode 380. O(1) 时间插入、删除和获取随机元素)