|
| 1 | +/** |
| 2 | + * 1146. Snapshot Array |
| 3 | + * https://leetcode.com/problems/snapshot-array/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Implement a SnapshotArray that supports the following interface: |
| 7 | + * - SnapshotArray(int length) initializes an array-like data structure with the given length. |
| 8 | + * Initially, each element equals 0. |
| 9 | + * - void set(index, val) sets the element at the given index to be equal to val. |
| 10 | + * - int snap() takes a snapshot of the array and returns the snapId: the total number of times |
| 11 | + * we called snap() minus 1. |
| 12 | + * - int get(index, snapId) returns the value at the given index, at the time we took the |
| 13 | + * snapshot with the given snapId |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number} length |
| 18 | + */ |
| 19 | +var SnapshotArray = function(length) { |
| 20 | + this.history = new Map(); |
| 21 | + this.snapshots = 0; |
| 22 | + this.length = length; |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} index |
| 27 | + * @param {number} val |
| 28 | + * @return {void} |
| 29 | + */ |
| 30 | +SnapshotArray.prototype.set = function(index, val) { |
| 31 | + const current = this.history.get(this.snapshots) || new Map(); |
| 32 | + current.set(index, val); |
| 33 | + this.history.set(this.snapshots, current); |
| 34 | +}; |
| 35 | + |
| 36 | +/** |
| 37 | + * @return {number} |
| 38 | + */ |
| 39 | +SnapshotArray.prototype.snap = function() { |
| 40 | + return this.snapshots++; |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * @param {number} index |
| 45 | + * @param {number} snapId |
| 46 | + * @return {number} |
| 47 | + */ |
| 48 | +SnapshotArray.prototype.get = function(index, snapId) { |
| 49 | + for (let id = snapId; id >= 0; id--) { |
| 50 | + const snapshot = this.history.get(id); |
| 51 | + if (snapshot && snapshot.has(index)) { |
| 52 | + return snapshot.get(index); |
| 53 | + } |
| 54 | + } |
| 55 | + return 0; |
| 56 | +}; |
0 commit comments