Skip to content

Commit c5502ee

Browse files
committed
github.com/masx200/leetcode-test/fancy-sequence
1 parent 9764281 commit c5502ee

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

fancy-sequence/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/masx200/leetcode-test/fancy-sequence
2+
3+
go 1.19

fancy-sequence/index.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package index
2+
3+
type Fancy struct {
4+
v, a, b []int
5+
}
6+
7+
func Constructor() Fancy {
8+
return Fancy{
9+
a: []int{1}, b: []int{0},
10+
}
11+
}
12+
13+
func (f *Fancy) Append(val int) {
14+
f.v = append(f.v, val)
15+
f.a = append(f.a, f.a[len(f.a)-1])
16+
f.b = append(f.b, f.b[len(f.b)-1])
17+
}
18+
19+
func (f *Fancy) AddAll(inc int) {
20+
f.b[len(f.b)-1] = (f.b[len(f.b)-1] + inc) % mod
21+
}
22+
23+
func (f *Fancy) MultAll(m int) {
24+
f.a[len(f.a)-1] = (f.a[len(f.a)-1] * m) % mod
25+
f.b[len(f.b)-1] = (f.b[len(f.b)-1] * m) % mod
26+
}
27+
28+
func (f *Fancy) GetIndex(idx int) int {
29+
if idx >= len(f.v) {
30+
return -1
31+
}
32+
ao := (MultiplicativeInverse(f.a[idx], mod) * f.a[len(f.a)-1]) % mod
33+
bo := (f.b[len(f.b)-1] - f.b[idx]*ao%mod + mod) % mod
34+
return (ao*f.v[idx]%mod + bo) % mod
35+
}
36+
func PowMod(x, y, m int) int {
37+
mod := int64(m)
38+
var ret int64 = 1
39+
var cur int64 = int64(x)
40+
for y != 0 {
41+
if y&1 != 0 {
42+
ret = (ret) * cur % mod
43+
}
44+
cur = cur * cur % mod
45+
y >>= 1
46+
}
47+
return int(ret)
48+
}
49+
func MultiplicativeInverse(x, m int) int {
50+
return PowMod(x, m-2, m)
51+
}
52+
53+
const mod = 1000000007

0 commit comments

Comments
 (0)