Skip to content

Commit 453f71b

Browse files
committed
Time: 695 ms (51.23%), Space: 45.7 MB (37.33%) - LeetHub
1 parent 3e6b264 commit 453f71b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class SnapshotArray:
2+
3+
def __init__(self, length: int):
4+
self.cur_id = 0
5+
self.curVals = [0] * length
6+
self.snapIdArr = [[-1] for _ in range(length)]
7+
self.arrVal = [[0] for _ in range(length)]
8+
self.modified = set()
9+
10+
def set(self, index: int, val: int) -> None:
11+
if val == self.arrVal[index][-1]:
12+
if index in self.modified: self.modified.remove(index)
13+
return
14+
self.curVals[index] = val
15+
if index not in self.modified: self.modified.add(index)
16+
17+
def snap(self) -> int:
18+
for idx in self.modified:
19+
self.snapIdArr[idx].append(self.cur_id)
20+
self.arrVal[idx].append(self.curVals[idx])
21+
self.modified.clear()
22+
self.cur_id += 1
23+
return self.cur_id - 1
24+
25+
def get(self, index: int, snap_id: int) -> int:
26+
arr = self.snapIdArr[index]
27+
l, r = 0, len(arr)
28+
while l < r:
29+
m = (l + r) // 2
30+
if arr[m] <= snap_id:
31+
l = m + 1
32+
else: r = m
33+
return self.arrVal[index][l-1]
34+
35+
36+
37+
# Your SnapshotArray object will be instantiated and called as such:
38+
# obj = SnapshotArray(length)
39+
# obj.set(index,val)
40+
# param_2 = obj.snap()
41+
# param_3 = obj.get(index,snap_id)

0 commit comments

Comments
 (0)