1146. Snapshot Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class SnapshotArray {

private final TreeMap<Integer, Integer>[] treeMaps;
private int snapId;

public SnapshotArray(int length) {
this.treeMaps = new TreeMap[length];
for (int i = 0; i < length; i++) {
this.treeMaps[i] = new TreeMap<>();
this.treeMaps[i].put(0, 0);
}
this.snapId = 0;
}

public void set(int index, int val) {
treeMaps[index].put(snapId, val);
}

public int snap() {
return snapId++;
}

public int get(int index, int snap_id) {
return treeMaps[index].floorEntry(snap_id).getValue();
}

}

Binary Search

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class SnapshotArray {

private int snapId;
private final Map<Integer, List<int[]>> map;

public SnapshotArray(int length) {
this.map = new HashMap<>();
}

public void set(int index, int val) {
List<int[]> pairList = map.get(index);
if (pairList == null) {
pairList = new ArrayList<>();
pairList.add(new int[]{val, snapId});
map.put(index, pairList);
} else {
int[] lastPair = pairList.get(pairList.size() - 1);
if (lastPair[1] == snapId) {
lastPair[0] = val;
} else {
pairList.add(new int[]{val, snapId});
}
}
}

public int snap() {
return snapId++;
}

public int get(int index, int snap_id) {
List<int[]> pairList = map.get(index);
if (pairList == null) {
return 0;
}

int left = 0, right = pairList.size() - 1;
while (left <= right) {
int mid = (left + right) >>> 1;
if (pairList.get(mid)[1] < snap_id) {
left = mid + 1;
} else if (pairList.get(mid)[1] > snap_id) {
right = mid - 1;
} else {
return pairList.get(mid)[0];
}
}

// now: right, left
return right == -1 ? 0 : pairList.get(right)[0];
}

}

References

1146. Snapshot Array