From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/snapshot_array.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 other/snapshot_array.cpp (limited to 'other/snapshot_array.cpp') diff --git a/other/snapshot_array.cpp b/other/snapshot_array.cpp new file mode 100644 index 0000000..42d165b --- /dev/null +++ b/other/snapshot_array.cpp @@ -0,0 +1,42 @@ +// 1146. Snapshot Array +#include "leetcode.h" + +/* + * implement a 'SnapshotArray' class that supports the following interface + * - 'SnapshotArray(int length)' initialises an array-like data structure with + * the given length. initially, each element equals zero. + * - 'void set(index, val)' sets the element at the given 'index' to be equal to + * 'val' + * - 'int snap()' takes a snapshot of the array and retusn the 'snap_id': the + * total number of times we called 'snap()' minus 1 + * - 'int get(index, snap_id)' returns the value at the given 'index', at the + * time we took the snapshot with the given 'snap_id' + */ + +class SnapshotArray { + int curr_snap = 0; + vector>> vvp; + +public: + SnapshotArray(int length) { vvp = vector>>(length); } + void set(int index, int val) { + if (vvp[index].empty() || vvp[index].back().first != curr_snap) + vvp[index].push_back({curr_snap, val}); + else + vvp[index].back().second = val; + } + int snap() { return curr_snap++; } + int get(int index, int snap_id) { + auto i = upper_bound(begin(vvp[index]), end(vvp[index]), + pair(snap_id, INT_MAX)); + return i == begin(vvp[index]) ? 0 : prev(i)->second; + } +}; + +int main() { + SnapshotArray *obj = new SnapshotArray(3); + obj->set(0, 5); + printf("%d\n", obj->snap()); // expect: 0 + obj->set(0, 6); + printf("%d\n", obj->get(0, 0)); // expect: 5 +} -- cgit v1.2.3