https://leetcode.com/problems/snapshot-array/description/
class SnapshotArray {
HashMap<Integer, HashMap<Integer, Integer>> snap = new HashMap<Integer, HashMap<Integer, Integer>>();
int snaped = -1;
public SnapshotArray(int length) {
snaped++;
}
public void set(int index, int val) {
if(!snap.containsKey(index)) {
snap.put(index, new HashMap<Integer, Integer>());
}
snap.get(index).put(snaped, val);
}
public int snap() {
snaped++;
return snaped-1;
}
public int get(int index, int snap_id) {
if(!snap.containsKey(index))
return 0;
if (snap.get(index).containsKey(snap_id)) {
return (Integer)snap.get(index).get(snap_id);
}
int prev = -1;
for (Map.Entry<Integer,Integer> entry : snap.get(index).entrySet()) {
int snapId = entry.getKey();
if(snapId < snap_id) {
if (prev == -1)
prev = snapId;
else if (snapId > prev) {
prev = snapId;
}
}
}
return snap.get(index).containsKey(prev) ? (Integer)snap.get(index).get(prev) : 0;
}
}
Here’s a breakdown of the code:
- The class
SnapshotArrayhas a member variablesnapwhich is a HashMap. This HashMap has an Integer key (representing the index) and a nested HashMap as its value. The nested HashMap has an Integer key (representing the snapshot ID) and an Integer value (representing the value at that index and snapshot). - The variable
snapedis an integer that keeps track of the current snapshot ID. It is initialized to -1. - The constructor
SnapshotArray(int length)initializes thesnapedvariable by incrementing it, indicating the creation of a new snapshot. - The method
set(int index, int val)is used to set the value at a specific index. It first checks if the index exists in thesnapHashMap. If not, it creates a new nested HashMap for that index. It then adds the value at the current snapshot ID to the nested HashMap. - The method
snap()is used to create a new snapshot. It increments thesnapedvariable and returns the previous snapshot ID. - The method
get(int index, int snap_id)is used to retrieve the value at a specific index and snapshot ID. It first checks if the index exists in thesnapHashMap. If not, it returns 0. If the index exists, it iterates over the entries of the nested HashMap for that index. It finds the latest snapshot ID that is less than the providedsnap_id. It then retrieves the value associated with that snapshot ID from the nested HashMap. If no such snapshot ID is found, it returns 0.