在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Implement a SnapshotArray that supports the following interface:
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:
实现支持下列接口的「快照数组」- SnapshotArray:
示例: 输入:["SnapshotArray","set","snap","set","get"] [[3],[0,5],[],[0,6],[0,0]] 输出:[null,null,0,null,5] 解释: SnapshotArray snapshotArr = new SnapshotArray(3); // 初始化一个长度为 3 的快照数组 snapshotArr.set(0,5); // 令 array[0] = 5 snapshotArr.snap(); // 获取快照,返回 snap_id = 0 snapshotArr.set(0,6); snapshotArr.get(0,0); // 获取 snap_id = 0 的快照中 array[0] 的值,返回 5 提示:
480ms
1 class SnapshotArray { 2 3 private var dict = [Int: Int]() 4 private var snapshots = [[Int: Int]]() 5 6 init(_ length: Int) { 7 //array = Array(repeating: 0, count: length + 1) 8 } 9 10 func set(_ index: Int, _ val: Int) { 11 dict[index] = val 12 } 13 14 func snap() -> Int { 15 snapshots.append(dict) 16 return snapshots.count - 1 17 } 18 19 func get(_ index: Int, _ snap_id: Int) -> Int { 20 return snapshots[snap_id][index] ?? 0 21 } 22 } 23 24 /** 25 * Your SnapshotArray object will be instantiated and called as such: 26 * let obj = SnapshotArray(length) 27 * obj.set(index, val) 28 * let ret_2: Int = obj.snap() 29 * let ret_3: Int = obj.get(index, snap_id) 30 */ Runtime: 828 ms Memory Usage: 27.8 MB
1 class SnapshotArray { 2 var vv:[[Int:Int]] = [[Int:Int]]() 3 4 init(_ length: Int) { 5 vv.append([Int:Int]()) 6 } 7 8 func set(_ index: Int, _ val: Int) { 9 vv[vv.count - 1][index] = val 10 } 11 12 func snap() -> Int { 13 vv.append([Int:Int]()) 14 return vv.count - 2 15 } 16 17 func get(_ index: Int, _ snap_id: Int) -> Int { 18 for i in stride(from:snap_id,through:0,by:-1) 19 { 20 if vv[i][index] != nil 21 { 22 return vv[i][index]! 23 } 24 } 25 return 0 26 } 27 } 28 29 /** 30 * Your SnapshotArray object will be instantiated and called as such: 31 * let obj = SnapshotArray(length) 32 * obj.set(index, val) 33 * let ret_2: Int = obj.snap() 34 * let ret_3: Int = obj.get(index, snap_id) 35 */
|
请发表评论