File tree 1 file changed +28
-22
lines changed
1 file changed +28
-22
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
* initialize your data structure here.
3
3
*/
4
- const MinStack = function ( ) {
5
- this . arr = [ ]
6
- } ;
4
+ const MinStack = function ( ) {
5
+ this . stack = [ ]
6
+ this . min = null
7
+ }
7
8
8
- /**
9
+ /**
9
10
* @param {number } x
10
11
* @return {void }
11
12
*/
12
- MinStack . prototype . push = function ( x ) {
13
- this . arr . push ( x )
14
- } ;
13
+ MinStack . prototype . push = function ( x ) {
14
+ if ( this . min === null ) {
15
+ this . min = x
16
+ } else {
17
+ this . min = Math . min ( x , this . min )
18
+ }
19
+ return this . stack . push ( x )
20
+ }
15
21
16
22
/**
17
23
* @return {void }
18
24
*/
19
- MinStack . prototype . pop = function ( ) {
20
- this . arr . pop ( )
21
- } ;
25
+ MinStack . prototype . pop = function ( ) {
26
+ let removed = this . stack . pop ( )
27
+ if ( this . min === removed ) {
28
+ this . min = this . stack . length > 0 ? Math . min ( ...this . stack ) : null
29
+ }
30
+ return this . stack
31
+ }
22
32
23
33
/**
24
34
* @return {number }
25
35
*/
26
- MinStack . prototype . top = function ( ) {
27
- return this . arr [ this . arr . length - 1 ]
28
- } ;
36
+ MinStack . prototype . top = function ( ) {
37
+ return this . stack [ this . stack . length - 1 ]
38
+ }
29
39
30
40
/**
31
41
* @return {number }
32
42
*/
33
- MinStack . prototype . getMin = function ( ) {
34
- let min = Number . MAX_VALUE
35
- for ( let el of this . arr ) {
36
- if ( el < min ) min = el
37
- }
38
- return min
39
- } ;
43
+ MinStack . prototype . getMin = function ( ) {
44
+ return this . min
45
+ }
40
46
41
- /**
47
+ /**
42
48
* Your MinStack object will be instantiated and called as such:
43
- * var obj = Object.create( MinStack).createNew ()
49
+ * var obj = new MinStack()
44
50
* obj.push(x)
45
51
* obj.pop()
46
52
* var param_3 = obj.top()
You can’t perform that action at this time.
0 commit comments