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