forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapshot-array.py
46 lines (36 loc) · 994 Bytes
/
snapshot-array.py
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
# Time: set: O(1)
# get: O(logn), n is the total number of set
# Space: O(n)
import collections
import bisect
class SnapshotArray(object):
def __init__(self, length):
"""
:type length: int
"""
self.__A = collections.defaultdict(lambda: [[0, 0]])
self.__snap_id = 0
def set(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if self.__A[index][-1][0] == self.__snap_id:
self.__A[index][-1][1] = val
else:
self.__A[index].append([self.__snap_id, val])
def snap(self):
"""
:rtype: int
"""
self.__snap_id += 1
return self.__snap_id - 1
def get(self, index, snap_id):
"""
:type index: int
:type snap_id: int
:rtype: int
"""
i = bisect.bisect_left(self.__A[index], [snap_id+1, float("-inf")]) - 1
return self.__A[index][i][1]