problems(cpp): add “1146. Snapshot Array”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-06-11 20:34:39 +02:00
parent ae267fed23
commit 931938ba38
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,63 @@
#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;
}