File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
solution/1300-1399/1381.Design a Stack With Increment Operation Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } maxSize
3
+ */
4
+ var CustomStack = function ( maxSize ) {
5
+ this . stk = Array ( maxSize ) . fill ( 0 ) ;
6
+ this . add = Array ( maxSize ) . fill ( 0 ) ;
7
+ this . i = 0 ;
8
+ } ;
9
+
10
+ /**
11
+ * @param {number } x
12
+ * @return {void }
13
+ */
14
+ CustomStack . prototype . push = function ( x ) {
15
+ if ( this . i < this . stk . length ) {
16
+ this . stk [ this . i ++ ] = x ;
17
+ }
18
+ } ;
19
+
20
+ /**
21
+ * @return {number }
22
+ */
23
+ CustomStack . prototype . pop = function ( ) {
24
+ if ( this . i <= 0 ) {
25
+ return - 1 ;
26
+ }
27
+ const ans = this . stk [ -- this . i ] + this . add [ this . i ] ;
28
+ if ( this . i > 0 ) {
29
+ this . add [ this . i - 1 ] += this . add [ this . i ] ;
30
+ }
31
+ this . add [ this . i ] = 0 ;
32
+ return ans ;
33
+ } ;
34
+
35
+ /**
36
+ * @param {number } k
37
+ * @param {number } val
38
+ * @return {void }
39
+ */
40
+ CustomStack . prototype . increment = function ( k , val ) {
41
+ if ( this . i > 0 ) {
42
+ this . add [ Math . min ( this . i , k ) - 1 ] += val ;
43
+ }
44
+ } ;
45
+
46
+ /**
47
+ * Your CustomStack object will be instantiated and called as such:
48
+ * var obj = new CustomStack(maxSize)
49
+ * obj.push(x)
50
+ * var param_2 = obj.pop()
51
+ * obj.increment(k,val)
52
+ */
You can’t perform that action at this time.
0 commit comments