题目
解法:二分搜索
建立一个list,每个list的位置是一个list,记录[snap_id,val]的pair。每次get的时候二分搜索等于这个snap id的right most位置或者第一个小于这个snap id的位置。bisect.bisect:1. bisect(list, num, beg, end) :- This function returns the position in the sorted list, where the number passed in argument can be placed so as to maintain the resultant list in sorted order. If the element is already present in the list, the right most position where element has to be inserted is returned. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered.
值得注意的是,这边二分搜索的不是值,而是[snap_id,val]的pair,所以需要把val设为最大值保证找到的是right most的位置或者直接去搜索snap id+1
class SnapshotArray:
def __init__(self, length: int):
self.A = [[[-1, 0]] for _ in range(length)]
self.snap_id = 0
def set(self, index: int, val: int) -> None:
self.A[index].append([self.snap_id, val])
def snap(self) -> int:
self.snap_id += 1
return self.snap_id - 1
def get(self, index: int, snap_id: int) -> int:
# print(self.A)
i = bisect.bisect(self.A[index], [snap_id,float('inf')])-1
# print(i)
return self.A[index][i][1]
# Your SnapshotArray object will be instantiated and called as such:
# obj = SnapshotArray(length)
# obj.set(index,val)
# param_2 = obj.snap()
# param_3 = obj.get(index,snap_id)
Time O(logS)
Space O(S)
where S is the number of set called.
参考:https://leetcode.com/problems/snapshot-array/discuss/350562/JavaPython-Binary-Search