-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsnapshot-array.go
49 lines (40 loc) · 994 Bytes
/
snapshot-array.go
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
package main
type value struct {
value int
snapshotID int
}
type SnapshotArray struct {
values [][]value
snapshotID int
}
func Constructor(length int) SnapshotArray {
values := make([][]value, length)
for i := range values {
values[i] = []value{{}}
}
return SnapshotArray{
values: values,
}
}
func (this *SnapshotArray) Set(index int, val int) {
if this.values[index][len(this.values[index])-1].snapshotID != this.snapshotID {
this.values[index] = append(this.values[index], value{})
}
this.values[index][len(this.values[index])-1] = value{val, this.snapshotID}
}
func (this *SnapshotArray) Snap() int {
this.snapshotID += 1
return this.snapshotID - 1
}
func (this *SnapshotArray) Get(index int, snap_id int) int {
left, right := 0, len(this.values[index])
for left < right {
mid := left + (right-left)/2
if this.values[index][mid].snapshotID <= snap_id {
left = mid + 1
} else {
right = mid
}
}
return this.values[index][left-1].value
}