problems(cpp): add “1146. Snapshot Array”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
ae267fed23
commit
931938ba38
1 changed files with 63 additions and 0 deletions
63
problems/cpp/snapshot-array.cpp
Normal file
63
problems/cpp/snapshot-array.cpp
Normal 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;
|
||||
}
|
Loading…
Reference in a new issue