3
unordered_map<int, vector<int>> toSnaps, toValues;6
SnapshotArray(int length) {10
void set(int index, int val) {11
if (toSnaps.count(index) == 0) {12
// After lower_bound, prevent returning negative lo13
toSnaps[index].push_back(-1);15
toValues[index].push_back(0);17
// same timestamp -> just update value18
if (toSnaps[index].back() == timestamp) {19
toValues[index].back() = val;21
// not -> add timestamp and value23
toSnaps[index].push_back(timestamp);24
toValues[index].push_back(val);32
int get(int index, int snap_id) {33
// check whether index exists or not34
if (toSnaps.count(index) == 0) return 0;35
auto &snaps = toSnaps[index];36
int lo = 0, hi = snaps.size() - 1;38
int m = lo + (hi - lo) / 2;39
if (snaps[m] >= snap_id)44
// lower bound can be larger than target45
if (snaps[lo] > snap_id) lo--;46
// if lo is negative, then ther is no value of index at lo time47
// if (lo < 0) return 0;48
return toValues[index][lo];53
* Your SnapshotArray object will be instantiated and called as such:54
* SnapshotArray* obj = new SnapshotArray(length);55
* obj->set(index,val);56
* int param_2 = obj->snap();57
* int param_3 = obj->get(index,snap_id);