File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: set: O(1)
2
+ // get: O(logn), n is the total number of set
3
+ // Space: O(n)
4
+
5
+ class SnapshotArray {
6
+ public:
7
+ SnapshotArray (int length) {
8
+ }
9
+
10
+ void set (int index, int val) {
11
+ if (!A_.count (index)) {
12
+ A_[index].emplace_back (-1 , 0 );
13
+ }
14
+ A_[index].emplace_back (snap_id_, val);
15
+ }
16
+
17
+ int snap () {
18
+ return snap_id_++;
19
+ }
20
+
21
+ int get (int index, int snap_id) {
22
+ if (!A_.count (index)) {
23
+ A_[index].emplace_back (-1 , 0 );
24
+ }
25
+ const auto & it = prev (upper_bound (A_[index].cbegin (), A_[index].cend (),
26
+ make_pair (snap_id + 1 , 0 )));
27
+ return it->second ;
28
+ }
29
+
30
+ private:
31
+ unordered_map<int , vector<pair<int , int >>> A_;
32
+ int snap_id_ = 0 ;
33
+ };
34
+
35
+ /* *
36
+ * Your SnapshotArray object will be instantiated and called as such:
37
+ * SnapshotArray* obj = new SnapshotArray(length);
38
+ * obj->set(index,val);
39
+ * int param_2 = obj->snap();
40
+ * int param_3 = obj->get(index,snap_id);
41
+ */
You can’t perform that action at this time.
0 commit comments