File tree Expand file tree Collapse file tree 1 file changed +28
-22
lines changed
Expand file tree Collapse file tree 1 file changed +28
-22
lines changed Original file line number Diff line number Diff line change 11/**
22 * initialize your data structure here.
33 */
4- const MinStack = function ( ) {
5- this . arr = [ ]
6- } ;
4+ const MinStack = function ( ) {
5+ this . stack = [ ]
6+ this . min = null
7+ }
78
8- /**
9+ /**
910 * @param {number } x
1011 * @return {void }
1112 */
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+ }
1521
1622/**
1723 * @return {void }
1824 */
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+ }
2232
2333/**
2434 * @return {number }
2535 */
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+ }
2939
3040/**
3141 * @return {number }
3242 */
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+ }
4046
41- /**
47+ /**
4248 * Your MinStack object will be instantiated and called as such:
43- * var obj = Object.create( MinStack).createNew ()
49+ * var obj = new MinStack()
4450 * obj.push(x)
4551 * obj.pop()
4652 * var param_3 = obj.top()
You can’t perform that action at this time.
0 commit comments