这题的测试方法是不是有问题???
1263
2021.01.04
发布于 未知归属地

题目:常数时间插入、删除和获取随机元素
简单说就是要实现一个数据结构可以以O(1)的复杂度插入、删除元素以及随机返回数据中的一项
我主要是想问一下随机返回数据中的一项getRandom方法的实现,官方是借助random.choice函数做的,但是我这么写提交之后报错:
无标题.png
这是什么意思?我生成的随机数还得和测试用例一样吗???那还叫随机数吗???
最后贴一下代码:

class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        import random
        self.val2ind = {}
        self.container = []


    def insert(self, val: int) -> bool:
        """
        Inserts a value to the set. Returns true if the set did not already contain the specified element.
        """
        if val in self.val2ind:
            return False
        self.container.append(val)
        self.val2ind[val] = len(self.container)
        return True


    def remove(self, val: int) -> bool:
        """
        Removes a value from the set. Returns true if the set contained the specified element.
        """
        if val not in self.val2ind:
            return False
        self.val2ind[self.container[-1]] = self.val2ind[val]
        self.container[self.val2ind.pop(val)] = self.container[-1]
        self.container.pop() 
        return True


    def getRandom(self) -> int:
        """
        Get a random element from the set.
        """
        return random.choice(self.container)

求大佬指教

评论 (2)