LeetCode #380 Insert Delete GetRandom O(1)

Forest uses index cords to find storage slots, fills a deletion gap with the last crate and samples through an even spinner

The key point of this problem is understanding “average O(1) time”, which is also an important concept in time-complexity analysis: “amortized”.
In Algorithms, Fourth Edition, the analysis of many data-structure operations uses this method. So “amortized time complexity” is often associated with operations on the corresponding data structure. When I interviewed at Megvii in May, the second problem asked me to construct a queue data structure that maintains the maximum value, and the final requirement was that the operation time complexity be “amortized O(1)”. Unfortunately, at that time I was not familiar with the concept of “amortized”. I could analyze worst-case time complexity, and although I eventually derived the correct answer under the interviewer’s guidance, the final result was predictably no hire.

Description: https://leetcode.com/problems/insert-delete-getrandom-o1/description/
Solution: None
Difficulty: Medium

answer

The key point is to use a hashmap for O(1) lookup, while ArrayList conveniently supports random access by index.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class RandomizedSet:

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


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 in self.index_map:
return False

self.index_map[val] = len(self.array)
self.array.append(val)

return True


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 not in self.index_map:
return False

self.array[self.index_map[val]] = self.array[-1]
self.index_map[self.array[-1]] = self.index_map[val]
self.array.pop()
self.index_map.pop(val)

return True


def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
rnd = random.randint(0, len(self.array)-1)

return self.array[rnd]



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