Skip to content

Commit cbcc15a

Browse files
authored
Create snapshot-array.py
1 parent cc1bbc6 commit cbcc15a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Python/snapshot-array.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Time: set: O(1)
2+
# get: O(logn), n is the total number of set
3+
# Space: O(n)
4+
5+
import collections
6+
import bisect
7+
8+
9+
class SnapshotArray(object):
10+
11+
def __init__(self, length):
12+
"""
13+
:type length: int
14+
"""
15+
self.__A = collections.defaultdict(lambda: [(-1, 0)])
16+
self.__snap_id = 0
17+
18+
19+
def set(self, index, val):
20+
"""
21+
:type index: int
22+
:type val: int
23+
:rtype: None
24+
"""
25+
self.__A[index].append((self.__snap_id, val))
26+
27+
28+
def snap(self):
29+
"""
30+
:rtype: int
31+
"""
32+
self.__snap_id += 1
33+
return self.__snap_id - 1
34+
35+
36+
def get(self, index, snap_id):
37+
"""
38+
:type index: int
39+
:type snap_id: int
40+
:rtype: int
41+
"""
42+
i = bisect.bisect_right(self.__A[index], (snap_id+1, 0)) - 1
43+
return self.__A[index][i][1]

0 commit comments

Comments
 (0)