[LeetCode] 1146. 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
  • At most 50000 calls will be made to setsnap, and get.
  • 0 <= index < length
  • 0 <= snap_id < (the total number of times we call snap())
  • 0 <= val <= 10^9

快照数组。题意是给一个长度为length的数组,我们会时不时地往里面放或者修改一些元素,同时我们有一个函数snap(),是对当下的数组做一个快照。需要实现这个design。

比较粗暴的想法肯定是无论数组做什么操作,当有snap()操作的时候,就无条件把数组整个复制一份。这样效率是很低的。比如你在打字的时候,你有时为了保险起见,多按了几次ctrl + S,如果保存的函数也是这样实现,那么实在是太低效了。一个优化的思路是,我们只需要在每次snap的时候,记录有变化的index即可;这也与get()函数呼应,因为get()函数也只在意某个snap_id背后的某一个index上的数字是多少。当之后再次被叫到某个snap_id的时候,我们也能够快速还原。

具体的实现是我们需要一个和length等长的list,来记录每个index上的数字;同时这个list上每个位置下还挂着一个treemap<Integer, Integer>,里面存的是<snapId, value>。所以当get()函数叫到某个index的时候,我拿到这个index上的treemap,此时我再用treemap中的floorEntry()函数拿到比当前snap_id小的最大的snapId。这样我就知道在这个index上最后一次被快照的数字是什么了。

初始化 - 时间O(n),空间O(n)

set() - 时间O(1)

snap() - 时间O(1)

get() - 时间O(1)

Java实现

 1 class SnapshotArray {
 2     private List<TreeMap<Integer, Integer>> list;
 3     private int snapId;
 4 
 5     public SnapshotArray(int length) {
 6         list = new ArrayList<>();
 7         for (int i = 0; i < length; i++) {
 8             list.add(new TreeMap<>());
 9             list.get(i).put(0, 0);
10         }
11         snapId = 0;
12     }
13 
14     public void set(int index, int val) {
15         list.get(index).put(snapId, val);
16     }
17 
18     public int snap() {
19         return snapId++;
20     }
21 
22     public int get(int index, int snap_id) {
23         return list.get(index).floorEntry(snap_id).getValue();
24     }
25 }
26 
27 /**
28  * Your SnapshotArray object will be instantiated and called as such:
29  * SnapshotArray obj = new SnapshotArray(length);
30  * obj.set(index,val);
31  * int param_2 = obj.snap();
32  * int param_3 = obj.get(index,snap_id);
33  */

 

LeetCode 题目总结

posted @ 2020-10-06 13:42  CNoodle  阅读(210)  评论(0编辑  收藏  举报