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