# 380. Insert Delete GetRandom O(1)

{% embed url="<https://leetcode.com/problems/insert-delete-getrandom-o1/>" %}

一开始被如何实现random给困住了，看解答发现可以用random module...

剩下的部分不难，利用hashmap 记录 {element: index}，要 remove 的时候用尾巴上的元素去覆盖掉需要 remove 的，再把尾巴 pop 掉，以实现O(1)的remove.

```python
import random

class RandomizedSet:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.data = []
        self.hash = dict()

    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.hash: 
            return False
        else:
            self.hash[val] = len(self.data)
            self.data.append(val)
            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.hash: 
            return False
        else:
            idx = self.hash[val]
            self.data[idx] = self.data[-1]
            self.hash[self.data.pop(-1)] = idx
            self.hash.pop(val)
            return True
        

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


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