|
| 1 | +# 380. Insert Delete GetRandom O(1) |
| 2 | + |
| 3 | +## Solution |
| 4 | +- Run-time: O(1) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of values |
| 7 | + |
| 8 | +When we insert or delete at O(1), we think of a dictionary. |
| 9 | +When we getRandom() at O(1) we think of a randomized index from an array. |
| 10 | +If we merge the two, we can achieve O(1). |
| 11 | +We just have to do some clever swapping and popping from the last element of the array. |
| 12 | + |
| 13 | +If we use the dictionary to store the value's index in relation to the array. |
| 14 | +When we insert, we can insert the new value to the end of the array and keep its value to index relationship in the dictionary. |
| 15 | + |
| 16 | +When it comes to removing the value, we can fetch the value's corresponding index then swap it with the last element in the array. |
| 17 | +Then we can just pop that element from the array. |
| 18 | +This will help us achieve O(1) run-time. |
| 19 | + |
| 20 | +``` |
| 21 | +class RandomizedSet: |
| 22 | +
|
| 23 | + def __init__(self): |
| 24 | + """ |
| 25 | + Initialize your data structure here. |
| 26 | + """ |
| 27 | + self.val_to_idx = dict() |
| 28 | + self.values = list() |
| 29 | +
|
| 30 | + def insert(self, val: int) -> bool: |
| 31 | + """ |
| 32 | + Inserts a value to the set. Returns true if the set did not already contain the specified element. |
| 33 | + """ |
| 34 | + if val in self.val_to_idx: |
| 35 | + return False |
| 36 | + self.values.append(val) |
| 37 | + self.val_to_idx[val] = len(self.values) - 1 |
| 38 | + return True |
| 39 | +
|
| 40 | +
|
| 41 | + def remove(self, val: int) -> bool: |
| 42 | + """ |
| 43 | + Removes a value from the set. Returns true if the set contained the specified element. |
| 44 | + """ |
| 45 | + if val not in self.val_to_idx: |
| 46 | + return False |
| 47 | + idx = self.val_to_idx[val] |
| 48 | + self.val_to_idx[self.values[-1]] = idx |
| 49 | + self.values[idx], self.values[-1] = self.values[-1], self.values[idx] |
| 50 | + del self.val_to_idx[val] |
| 51 | + self.values.pop() |
| 52 | + return True |
| 53 | +
|
| 54 | + def getRandom(self) -> int: |
| 55 | + """ |
| 56 | + Get a random element from the set. |
| 57 | + """ |
| 58 | + return self.values[random.randrange(0, len(self.values))] |
| 59 | +``` |
0 commit comments