LeetCode 1146. Snapshot Array
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1146. Snapshot Array相关的知识,希望对你有一定的参考价值。
原题链接在这里: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 givenindex
to be equal toval
.int snap()
takes a snapshot of the array and returns thesnap_id
: the total number of times we calledsnap()
minus1
.int get(index, snap_id)
returns the value at the givenindex
, at the time we took the snapshot with the givensnap_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
- At most
50000
calls will be made toset
,snap
, andget
. 0 <= index < length
0 <= snap_id <
(the total number of times we callsnap()
)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 */
以上是关于LeetCode 1146. Snapshot Array的主要内容,如果未能解决你的问题,请参考以下文章