Advertisement
Guest User

Grokking 233

a guest
Sep 7th, 2022
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. class SnapshotArray {
  2.  
  3.     // Store the snapshots of each cell, not the whole array
  4.     List<TreeMap<Integer, Integer>> arr;
  5.    
  6.     // Current snapshot number
  7.     int current = 0;
  8.  
  9.     // We need to initialize the array length from the start
  10.     public SnapshotArray(int length) {
  11.         arr = new ArrayList<>(length);
  12.         for (int i = 0; i < length; i++) {
  13.             arr.add(new TreeMap<Integer, Integer>());
  14.             arr.get(i).put(0, 0);
  15.         }
  16.     }
  17.  
  18.     // Set the new value to the *current* snapshot of the cell at index *index*
  19.     public void set(int index, int val) {
  20.         arr.get(index).put(current, val);
  21.     }
  22.  
  23.     public int snap() {
  24.         return current++;
  25.     }
  26.  
  27.     // In case number of "set" calls for a cell is less than total number of "snap" calls,
  28.     // we have to get the "newest" snapshot available for that cell
  29.     public int get(int index, int snap_id) {
  30.         return arr.get(index).floorEntry(snap_id).getValue();
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement