File tree 1 file changed +71
-1
lines changed
1 file changed +71
-1
lines changed Original file line number Diff line number Diff line change @@ -62,4 +62,74 @@ class MinStack {
62
62
* int param_3 = obj.top();
63
63
* int param_4 = obj.getMin();
64
64
*/
65
- ```
65
+ ```
66
+
67
+
68
+ 然后还可以再优化一点点, 就是在辅助栈存最小值的索引, 这样可以避免辅助栈的大量的重复元素的情况.
69
+
70
+ ``` JavaScript
71
+ /**
72
+ * initialize your data structure here.
73
+ */
74
+ const MinStack = function () {
75
+ this .arr = [];
76
+ this .help = [];
77
+ };
78
+
79
+ /**
80
+ * @param {number} x
81
+ * @return {void}
82
+ */
83
+ MinStack .prototype .push = function (x ) {
84
+ this .arr .push (x);
85
+ if (this .help .length === 0 ){
86
+ this .help .push (0 );
87
+ }else {
88
+ let min = this .getMin ();
89
+ if (x < min){
90
+ this .help .push (this .arr .length - 1 );
91
+ }
92
+ }
93
+ };
94
+
95
+ /**
96
+ * @return {void}
97
+ */
98
+ MinStack .prototype .pop = function () {
99
+ if (this .arr .length === 0 ){
100
+ throw new Error (' ???' );
101
+ }
102
+ if (this .arr .length - 1 === this .help [this .help .length - 1 ]){
103
+ this .help .pop ();
104
+ }
105
+ this .arr .pop ();
106
+ };
107
+
108
+ /**
109
+ * @return {number}
110
+ */
111
+ MinStack .prototype .top = function () {
112
+ return this .arr [this .arr .length - 1 ];
113
+ };
114
+
115
+ /**
116
+ * @return {number}
117
+ */
118
+ MinStack .prototype .getMin = function () {
119
+ if (this .arr .length === 0 ){
120
+ throw new Error (" ???" );
121
+ }
122
+ return this .arr [this .help [this .help .length - 1 ]];
123
+ };
124
+
125
+ /**
126
+ * Your MinStack object will be instantiated and called as such:
127
+ * var obj = Object.create(MinStack).createNew()
128
+ * obj.push(x)
129
+ * obj.pop()
130
+ * var param_3 = obj.top()
131
+ * var param_4 = obj.getMin()
132
+ */
133
+
134
+ ```
135
+
You can’t perform that action at this time.
0 commit comments