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 @   johnny_zhao  阅读(69)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示