1146. Snapshot Array

package LeetCode_1146

/**
 * 1146. Snapshot Array
 * https://leetcode.com/problems/snapshot-array/
 * Implement a SnapshotArray that supports the following interface:
1. SnapshotArray(int length) initializes an array-like data structure with the given length.Initially, each element equals 0.
2. void set(index, val) sets the element at the given index to be equal to val.
3. int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
4. 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. 1 <= length <= 50000
2. At most 50000 calls will be made to set, snap, and get.
3. 0 <= index < length
4. 0 <= snap_id < (the total number of times we call snap())
5. 0 <= val <= 10^9
 * */
class SnapshotArray(length: Int) {
    /*
    * solution: List+HashMap, key of map:index, value of map:`val`
    * Space complexity: O(length)
    * */
    val list = ArrayList<HashMap<Int, Int>>()

    init {
        list.add(HashMap())
    }

    //Time: O(1)
    fun set(index: Int, `val`: Int) {
        list.get(list.lastIndex).put(index, `val`)
    }

    //Time: O(1)
    fun snap(): Int {
        list.add(HashMap())
        return list.size - 2
    }

    //Time: O(snap_id)
    fun get(index: Int, snap_id: Int): Int {
        //scan from last to first, return the most recent change up to this snap_id,
        for (i in snap_id downTo 0) {
            if (list.get(i) != null && list.get(i).containsKey(index)) {
                return list.get(i).get(index)!!
            }
        }
        return 0
    }

}
/**
 * Your SnapshotArray object will be instantiated and called as such:
 * var obj = SnapshotArray(length)
 * obj.set(index,`val`)
 * var param_2 = obj.snap()
 * var param_3 = obj.get(index,snap_id)
 */

 

posted @ 2020-12-26 23:26  johnny_zhao  阅读(64)  评论(0编辑  收藏  举报