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)
     */
  • 相关阅读:
    C语言宏的定义和宏的使用方法(#define)
    C语言字符串拼接
    OC字符串与C语言字符串之间的相互转换
    C语言#include的用法
    NSSet集合
    NSArray 数组
    预定义宏,C语言预定义的宏详解
    主流C语言编译器介绍
    无法使用此电子邮件地址。请选择其他电子邮件地址
    可变大小、颜色边框、样式的UISwitch
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14194963.html
Copyright © 2011-2022 走看看