Neunomizuの日記

俺だけが俺だけじゃない

# LeetCode Medium 380. Insert Delete GetRandom O(1)

tags: leetcode

問題

イデア

ハッシュ関数を用いたSetを実装する問題です.

解法

  • 辞書を使うことで,実装します.

計算量

以下は時間計算量,空間計算量の順です.

  • __init__
    • $O(1)$
    • $O(1)$
  • insert
    • $O(1)$
    • $O(1)$
  • remove
    • $O(1)$
    • $O(1)$
  • `getRandom
    • $O(1)$
    • $O(1)$

Python

class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.nums = []
        self.idx = {}
        
    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.idx:
            return False
        
        self.nums.append(val)
        self.idx[val] = len(self.nums) - 1
        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.idx:
            return False
        
        idx, last = self.idx[val], self.nums[-1]
        self.nums[idx], self.idx[last] = last, idx
        self.nums.pop()
        del self.idx[val]
        return True
        

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


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