Using a HashTable directly but got accepted...


  • 0
    class RandomizedSet(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.elements = dict()
            
    
        def insert(self, val):
            """
            Inserts a value to the set. Returns true if the set did not already contain the specified element.
            :type val: int
            :rtype: bool
            """
            if val in self.elements:
                return False
            else:
                self.elements[val] = 0
                return True
            
    
        def remove(self, val):
            """
            Removes a value from the set. Returns true if the set contained the specified element.
            :type val: int
            :rtype: bool
            """
            if val in self.elements:
                self.elements.pop(val)
                return True
            else:
                return False
            
    
        def getRandom(self):
            """
            Get a random element from the set.
            :rtype: int
            """
            from random import randint
            
            return self.elements.keys()[randint(0, len(self.elements) - 1)]
    

Log in to reply
 

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