Python O(1)

  • 0
    class RandomizedSet(object):
        def __init__(self):
            self.eles, self.dic = [], {}
        def insert(self, val):
            if not val in self.dic:
                self.dic[val] = len(self.eles) - 1
                return True
            return False
        def remove(self, val):
            if val in self.dic:
                idx = self.dic[val]
                self.eles[idx], self.eles[-1] = self.eles[-1], self.eles[idx]
                self.dic[self.eles[idx]] = idx
                del self.dic[val]
                return True
            return False
        def getRandom(self):
            rdm = random.randint(0, len(self.eles) - 1)
            return self.eles[rdm]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.