-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertDeleteRandom.py
More file actions
57 lines (44 loc) · 1.12 KB
/
Copy pathInsertDeleteRandom.py
File metadata and controls
57 lines (44 loc) · 1.12 KB
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
import random
"""
Data Structure supports the following operations:
Insert - O(1)
Delete - O(1)
GetRandom - O(1)
Note: This version does not allow duplicates
"""
class InsertDeleteRandom:
def __init__(self):
self. _arr = []
self. _map = {}
"""
Tries to insert val into the list.
:param val: value to be inserted
:returns: true if insert success, false if already exists
"""
def insert(self, val):
if val in self._map: return False
self._map[val] = len(self._arr)
self._arr.append(val)
return True
"""
Tries to delete val from list.
:param val: value to be deleted
:returns: true if delete success, false if DNE
"""
def delete(self, val):
if val not in self._map: return False
p = self._map[val] # position of val
if p != len(self._arr) - 1:
self._arr[p], self._arr[-1] = self._arr[-1], self._arr[p]
self._map[self._arr[p]] = p
self._arr.pop()
del self._map[val]
return True
"""
Returns a random element from list
:returns: random element within list
"""
def get_random(self):
return not self.is_empty() and random.choice(self._arr)
def is_empty(self):
return len(self._arr) > 0