forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
snapshot-array.py
43 lines (33 loc) · 872 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
# 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: [(-1, 0)])
self.__snap_id = 0
def set(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
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_right(self.__A[index], (snap_id+1, 0)) - 1
return self.__A[index][i][1]