1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/cpp/snapshot-array.cpp

53 lines
1.2 KiB
C++
Raw Normal View History

#include <algorithm>
#include <cassert>
#include <map>
#include <vector>
class SnapshotArray {
int snap_id = 0;
std::vector<std::map<int, int>> arr;
public:
SnapshotArray(int length) : arr(length, std::map<int, int>{{0, 0}}) {}
void set(int index, int val) { arr[index][snap_id] = val; }
int snap() { return snap_id++; }
int get(int index, int snap_id) {
auto it = std::prev(arr[index].lower_bound(snap_id + 1));
return it == arr[index].end() ? 0 : it->second;
}
};
/**
* Your SnapshotArray object will be instantiated and called as such:
* SnapshotArray* obj = new SnapshotArray(length);
* obj->set(index,val);
* int param_2 = obj->snap();
* int param_3 = obj->get(index,snap_id);
*/
int main() {
SnapshotArray arr(3);
arr.set(0, 5);
assert(arr.snap() == 0);
arr.set(0, 6);
assert(arr.get(0, 0) == 5);
assert(arr.get(0, 1) == 6);
arr = SnapshotArray(1);
arr.set(0, 15);
assert(arr.snap() == 0);
assert(arr.snap() == 1);
assert(arr.snap() == 2);
assert(arr.get(0, 2) == 15);
assert(arr.snap() == 3);
assert(arr.snap() == 4);
assert(arr.get(0, 0) == 15);
return 0;
}