forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFancy Sequence.js
66 lines (57 loc) · 1.37 KB
/
Fancy Sequence.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
57
58
59
60
61
62
63
64
65
66
// Runtime: 7163 ms (Top 34.61%) | Memory: 115.6 MB (Top 69.23%)
var Fancy = function() {
this.sequence = [];
this.appliedOps = [];
this.ops = [];
this.modulo = Math.pow(10, 9) + 7;
};
/**
* @param {number} val
* @return {void}
*/
Fancy.prototype.append = function(val) {
this.sequence.push(val);
this.appliedOps.push(this.ops.length);
};
/**
* @param {number} inc
* @return {void}
*/
Fancy.prototype.addAll = function(inc) {
this.ops.push(['add', inc]);
};
/**
* @param {number} m
* @return {void}
*/
Fancy.prototype.multAll = function(m) {
this.ops.push(['mult', m]);
};
/**
* @param {number} idx
* @return {number}
*/
Fancy.prototype.getIndex = function(idx) {
if (idx >= this.sequence.length) {
return -1;
}
while (this.appliedOps[idx] < this.ops.length) {
const [operation, value] = this.ops[this.appliedOps[idx]];
this.appliedOps[idx]++;
if (operation === 'mult') {
this.sequence[idx] = (this.sequence[idx] * value) % this.modulo;
}
if (operation === 'add') {
this.sequence[idx] = (this.sequence[idx] + value) % this.modulo;
}
}
return this.sequence[idx];
};
/**
* Your Fancy object will be instantiated and called as such:
* var obj = new Fancy()
* obj.append(val)
* obj.addAll(inc)
* obj.multAll(m)
* var param_4 = obj.getIndex(idx)
*/