zoukankan      html  css  js  c++  java
  • 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)
     */
  • 相关阅读:
    干货—MySQL常见的面试题+索引原理分析!
    如何设计一个百万级的消息推送系统
    【金三银四跳槽季】Java工程师如何在1个月内做好面试准备?
    Nginx实现请求的负载均衡 + keepalived实现Nginx的高可用
    java函数式编程之Supplier
    SpringMVC + MyBatis + Mysql + Redis(作为二级缓存) 配置
    Redis创建集群报错
    阿里云服务器Tomcat无法从外部访问
    SSM框架学习之高并发秒杀业务--笔记5-- 并发优化
    在windows上部署使用Redis
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14194963.html
Copyright © 2011-2022 走看看