From 931938ba380383cc06fd97e230c42f15703858c7 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 11 Jun 2023 20:34:39 +0200 Subject: [PATCH] =?UTF-8?q?problems(cpp):=20add=20=E2=80=9C1146.=20Snapsho?= =?UTF-8?q?t=20Array=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/cpp/snapshot-array.cpp | 63 +++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 problems/cpp/snapshot-array.cpp diff --git a/problems/cpp/snapshot-array.cpp b/problems/cpp/snapshot-array.cpp new file mode 100644 index 0000000..f0e2962 --- /dev/null +++ b/problems/cpp/snapshot-array.cpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include + +class SnapshotArray { + int snap_id = 0; + std::vector> arr; + +public: + SnapshotArray(int length) + : arr(length, std::map { { 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; +}