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]; } }
return right == -1 ? 0 : pairList.get(right)[0]; }
}
|