[Array] LeetCode 380. Insert Delete GetRandom O(1)
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import random
class RandomizedSet:
def __init__(self):
self.data_map = {}
self.data = []
def insert(self, val: int) -> bool:
if val not in self.data_map:
idx = len(self.data)
self.data_map[val] = idx
self.data.append(val)
return True
return False
def remove(self, val: int) -> bool:
if val not in self.data_map:
return False
idx_of_cur_val = self.data_map[val]
last_element = self.data[-1]
self.data_map[last_element] = idx_of_cur_val
self.data[idx_of_cur_val] = last_element
self.data[-1] = val
self.data.pop()
self.data_map.pop(val)
return True
def getRandom(self) -> int:
return random.choice(self.data)
- The tricky part for this question is the
remove()
function. - We can use a set to remove the val, but we can’t do this since we have to use
random.choice(list)
forgetRandom()
, which only supports list type. - For the hash map, set the index as the value for the key.
- Swap the position with the value to be removed and the last element in the array.
- After swapping the position, use
pop()
to remove the val from the array.
This post is licensed under CC BY 4.0 by the author.