-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1146. Snapshot Array.java
More file actions
79 lines (71 loc) · 2.29 KB
/
1146. Snapshot Array.java
File metadata and controls
79 lines (71 loc) · 2.29 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
__________________________________________________________________________My Solution 2________________________________________________________________________________________
class SnapshotArray {
// improve use array instead of hashmap
// critical point is how to clone original arr to recorder, clone will MLE
// only record 0 to maxIdx data to recorder;
int id, len, maxIdx = 0;
List<int[]> recorder;
int[] cur;
public SnapshotArray(int length) {
id = 0;
len = length;
cur = new int[length];
recorder = new ArrayList<int[]>();
}
public void set(int index, int val) {
if(index < len){
maxIdx = Math.max(maxIdx, index);
cur[index] = val;
}
}
public int snap() {
int[] record = new int[maxIdx + 1];
for(int i = 0; i <= maxIdx; ++i){
record[i] = cur[i];
}
recorder.add(record);
return id++;
}
public int get(int index, int snap_id) {
int[] record = recorder.get(snap_id);
if(snap_id >= id || record.length <= index){
return 0;
}
return recorder.get(snap_id)[index];
}
}
/**
* Your SnapshotArray object will be instantiated and called as such:
* SnapshotArray obj = new SnapshotArray(length);
* obj.set(index,val);
* int param_2 = obj.snap();
* int param_3 = obj.get(index,snap_id);
*/
__________________________________________________________________________My Solution 1________________________________________________________________________________________
class SnapshotArray {
//use hashmap as records to store snapshot
int id, len;
List<HashMap<Integer, Integer>> recorder;
HashMap<Integer, Integer> cur;
public SnapshotArray(int length) {
id = 0;
len = length;
recorder = new ArrayList();
cur = new HashMap();
}
public void set(int index, int val) {
if(index <= len){
cur.put(index, val);
}
}
public int snap() {
recorder.add((HashMap<Integer, Integer>)cur.clone());
return id++;
}
public int get(int index, int snap_id) {
if(snap_id > id){
return -1;
}
return recorder.get(snap_id).getOrDefault(index, 0);
}
}