forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fancy-sequence.py
85 lines (71 loc) · 1.85 KB
/
fancy-sequence.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Time: O(1)
# Space: O(n)
MOD = 10**9+7
class Fancy(object):
def __init__(self):
self.__arr = []
self.__ops = [[1, 0]]
def append(self, val):
"""
:type val: int
:rtype: None
"""
self.__arr.append(val)
self.__ops.append(self.__ops[-1][:])
def addAll(self, inc):
"""
:type inc: int
:rtype: None
"""
self.__ops[-1][1] = (self.__ops[-1][1]+inc) % MOD
def multAll(self, m):
"""
:type m: int
:rtype: None
"""
self.__ops[-1] = [(self.__ops[-1][0]*m) % MOD, (self.__ops[-1][1]*m) % MOD]
def getIndex(self, idx):
"""
:type idx: int
:rtype: int
"""
if idx >= len(self.__arr):
return -1
a1, b1 = self.__ops[idx]
a2, b2 = self.__ops[-1]
a = a2*pow(a1, MOD-2, MOD)%MOD # O(logMOD), we treat it as O(1) here
b = (b2 - b1*a) % MOD
return (self.__arr[idx]*a + b) % MOD
# Time: O(1)
# Space: O(n)
class Fancy2(object):
def __init__(self):
self.__arr = []
self.__op = [1, 0]
def append(self, val):
"""
:type val: int
:rtype: None
"""
self.__arr.append((val-self.__op[1])*pow(self.__op[0], MOD-2, MOD)%MOD) # O(logMOD), we treat it as O(1) here
def addAll(self, inc):
"""
:type inc: int
:rtype: None
"""
self.__op[1] = (self.__op[1]+inc) % MOD
def multAll(self, m):
"""
:type m: int
:rtype: None
"""
self.__op = [(self.__op[0]*m) % MOD, (self.__op[1]*m) % MOD]
def getIndex(self, idx):
"""
:type idx: int
:rtype: int
"""
if idx >= len(self.__arr):
return -1
a, b = self.__op
return (self.__arr[idx]*a + b) % MOD