Dashboard Temp Share Shortlinks Frames API

HTMLify

LeetCode - Insert Delete GetRandom O(1) - Duplicates allowed - Python
Views: 456 | Author: abh
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from random import choice
class RandomizedCollection:

    def __init__(self):
        self.values = []

    def insert(self, val: int) -> bool:
        exist = not val in self.values
        self.values.append(val)
        return exist

    def remove(self, val: int) -> bool:
        exist = val in self.values
        if val in self.values:
            self.values.remove(val)
        return exist

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


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