Input:
["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output:
[null,null,0,null,5]
Explanation:
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5); // Set array[0] = 5
snapshotArr.snap(); // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5
To efficiently support snapshots and queries, we store a history of value changes for each index, along with the snapshot id when the change occurred. This allows us to quickly retrieve the value at any index for any snapshot using binary search.
#include<vector>#include<algorithm>usingnamespace std;
classSnapshotArray {
vector<vector<pair<int, int>>> arr;
int snap_id =0;
public: SnapshotArray(int length) : arr(length) {}
voidset(int index, int val) {
arr[index].emplace_back(snap_id, val);
}
intsnap() {
return snap_id++;
}
intget(int index, int snap_id) {
auto& v = arr[index];
int l =0, r = v.size() -1, ans =0;
while (l <= r) {
int m = l + (r - l) /2;
if (v[m].first <= snap_id) {
ans = v[m].second;
l = m +1;
} else {
r = m -1;
}
}
return ans;
}
};