Advertisement
Guest User

Grokking 233

a guest
Sep 7th, 2022
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. class SnapshotArray {
  2.    
  3.     // 0-indexed list of snapshots. Each snapshot is a hashtable (i.e. a HashMap in Java).
  4.     List<Map<Integer, Integer>> snapshots = new ArrayList<>();
  5.     Map<Integer, Integer> current = new HashMap<>();
  6.    
  7.     // Since Java Collection data structures dynamically allocate their size, we don't need to handle array maximum length.
  8.     public SnapshotArray(int length) { }
  9.    
  10.     // New data will be set as a Key-Value entry to the current snapshot.
  11.     public void set(int index, int val) {
  12.         current.put(index, val);
  13.     }
  14.    
  15.     // Each new snapshot is a copy of the previous hashtable.
  16.     public int snap() {
  17.         snapshots.add(new HashMap<>(current));
  18.         current = new HashMap<>(current);
  19.         return snapshots.size() - 1;
  20.     }
  21.    
  22.     public int get(int index, int snap_id) {
  23.         Integer val = snapshots.get(snap_id).get(index);
  24.         return val == null ? 0 : val;
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement