-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy path1146. Snapshot Array.ts
44 lines (40 loc) · 1.09 KB
/
1146. Snapshot Array.ts
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
class SnapshotArray {
// snap[i]: list of [snap_id, snap_value]
_snap: Array<Array<[number, number]>>
a: number[]
cnt = 0
changed: Set<number>
constructor (length: number) {
this._snap = Array(length).fill(0).map(() => [])
this.a = Array(length).fill(0)
this.changed = new Set(Array(length).fill(0).map((_, idx) => idx))
}
set (index: number, val: number): void {
this.a[index] = val
this.changed.add(index)
}
snap (): number {
for (const idx of this.changed) {
this._snap[idx].push([this.cnt, this.a[idx]])
}
this.changed.clear()
return this.cnt++
}
get (index: number, snap_id: number): number {
const n = this._snap[index].length
let l = 0; let r = n - 1
while (l < r) {
const mid = l + r + 1 >> 1
if (this._snap[index][mid][0] <= snap_id) l = mid
else r = mid - 1
}
return this._snap[index][l][1]
}
}
/**
* Your SnapshotArray object will be instantiated and called as such:
* var obj = new SnapshotArray(length)
* obj.set(index,val)
* var param_2 = obj.snap()
* var param_3 = obj.get(index,snap_id)
*/