Skip to content

Commit 8d4fcf5

Browse files
authored
Update snapshot-array.cpp
1 parent 1df3631 commit 8d4fcf5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C++/snapshot-array.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,39 @@ class SnapshotArray {
77
SnapshotArray(int length) {
88
}
99

10+
void set(int index, int val) {
11+
if (!A_.count(index)) {
12+
A_[index].emplace_back(0, 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(0, 0);
24+
}
25+
const auto& it = prev(lower_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+
// Time: set: O(logn)
36+
// get: O(logn), n is the total number of set
37+
// Space: O(n)
38+
class SnapshotArray2 {
39+
public:
40+
SnapshotArray(int length) {
41+
}
42+
1043
void set(int index, int val) {
1144
if (!A_.count(index)) {
1245
A_[index][0] = 0;

0 commit comments

Comments
 (0)