3. Snapshot Array
Implement a SnapshotArray that supports the following interface:
SnapshotArray(int length)
initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val)
sets the element at the givenindex
to be equal toval
.int snap()
takes a snapshot of the array and returns thesnap_id
: the total number of times we calledsnap()
minus1
.int get(index, snap_id)
returns the value at the givenindex
, at the time we took the snapshot with the givensnap_id
Example 1:
Solution: (Binary Search)
Approach: Instead of copy the whole array, we can only record the changes of the index
Time Complexity:
SnapshotArray(int length) is O(N) time
set(int index, int val) is O(log snap)
snap() is O(1)
get(int index, int snap_id) is O(log Snap)
Last updated