标签:object xpl which value structure nbsp public space ems
原题链接在这里:https://leetcode.com/problems/snapshot-array/
题目:
Implement a SnapshotArray that supports the following interface:
SnapshotArray(int length)
initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val)
sets the element at the given index
to be equal to val
.int snap()
takes a snapshot of the array and returns the snap_id
: the total number of times we called snap()
minus 1
.int get(index, snap_id)
returns the value at the given index
, at the time we took the snapshot with the given snap_id
Example 1:
Input: ["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation: SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3 snapshotArr.set(0,5); // Set array[0] = 5 snapshotArr.snap(); // Take a snapshot, return snap_id = 0 snapshotArr.set(0,6); snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5
Constraints:
1 <= length <= 50000
50000
calls will be made to set
, snap
, and get
.0 <= index < length
0 <= snap_id <
(the total number of times we call snap()
)0 <= val <= 10^9
题解:
Instead of make a copy of each snapshot, which takes a lot of memory space, we could record the state of cell when calling set method.
Have a TreeMap array, each TreeMap maintains the states of a cell.
When calling set, mark current snapshot id with the new value of this cell.
When calling get, try to get the floor entry with given snapshot id.
Time Complexity: SnapshotArray, O(length). set, O(logn). snap, O(1). get, O(logn). n is the number of total entries in arr, the number of previoius set call.
Space: O(n).
AC Java:
1 class SnapshotArray { 2 TreeMap<Integer, Integer> [] arr; 3 int snapId; 4 5 public SnapshotArray(int length) { 6 arr = new TreeMap[length]; 7 for(int i = 0; i<length; i++){ 8 arr[i] = new TreeMap<Integer, Integer>(); 9 arr[i].put(0, 0); 10 } 11 12 snapId = 0; 13 } 14 15 public void set(int index, int val) { 16 arr[index].put(snapId, val); 17 } 18 19 public int snap() { 20 return snapId++; 21 } 22 23 public int get(int index, int snap_id) { 24 return arr[index].floorEntry(snap_id).getValue(); 25 } 26 } 27 28 /** 29 * Your SnapshotArray object will be instantiated and called as such: 30 * SnapshotArray obj = new SnapshotArray(length); 31 * obj.set(index,val); 32 * int param_2 = obj.snap(); 33 * int param_3 = obj.get(index,snap_id); 34 */
标签:object xpl which value structure nbsp public space ems
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12041830.html