Skip to content

Latest commit

 

History

History
63 lines (51 loc) · 1.46 KB

380.md

File metadata and controls

63 lines (51 loc) · 1.46 KB

380. Insert Delete GetRandom O(1)

Solution 1 (time O(1), space O(n))

class RandomizedSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.vals = []
        self.idxs = {}


    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 not in self.idxs:
            self.vals.append(val)
            self.idxs[val] = len(self.vals) - 1
            return True
        else:
            return False


    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.idxs:
            cur_out = self.idxs[val]
            cur_in = self.vals[-1]
            self.vals[cur_out] = cur_in
            self.idxs[cur_in] = cur_out
            self.vals.pop()
            del self.idxs[val]
            return True
        else:
            return False


    def getRandom(self):
        """
        Get a random element from the set.
        :rtype: int
        """
        import random
        return random.choice(self.vals)



# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()