File tree 1 file changed +50
-1
lines changed
1 file changed +50
-1
lines changed Original file line number Diff line number Diff line change @@ -30,7 +30,7 @@ top也是直接返回栈顶元素即可。 这种做法每次修改栈都需要
30
30
31
31
![ 155.min-stack] ( ../assets/problems/155.min-stack-1.png )
32
32
33
- 是否有更高效的算法呢?答案是有的。
33
+ 是否有更高效的算法呢?答案是有的。
34
34
35
35
我们每次入栈的时候,保存的不再是真正的数字,而是它与当前最小值的差(当前元素没有入栈的时候的最小值)。
36
36
这样我们pop和top的时候拿到栈顶元素再加上** 上一个** 最小值即可。
@@ -60,6 +60,10 @@ pop或者top的时候:
60
60
61
61
## 代码
62
62
63
+ * 语言支持:JS,Python
64
+
65
+ Javascript Code:
66
+
63
67
``` js
64
68
/*
65
69
* @lc app=leetcode id=155 lang=javascript
@@ -131,3 +135,48 @@ MinStack.prototype.getMin = function() {
131
135
*/
132
136
```
133
137
138
+ Python Code:
139
+
140
+ ``` python
141
+ class MinStack :
142
+
143
+ def __init__ (self ):
144
+ """
145
+ initialize your data structure here.
146
+ """
147
+ self .min = float (' inf' )
148
+ self .stack = []
149
+
150
+ def push (self , x : int ) -> None :
151
+ self .stack.append(x - self .min)
152
+ if x < self .min:
153
+ self .min = x
154
+
155
+ def pop (self ) -> None :
156
+ if not self .stack:
157
+ return
158
+ tmp = self .stack.pop()
159
+ if tmp < 0 :
160
+ self .min -= tmp
161
+
162
+ def top (self ) -> int :
163
+ if not self .stack:
164
+ return
165
+ tmp = self .stack[- 1 ]
166
+ if tmp < 0 :
167
+ return self .min
168
+ else :
169
+ return self .min + tmp
170
+
171
+ def getMin (self ) -> int :
172
+ return self .min
173
+
174
+
175
+
176
+ # Your MinStack object will be instantiated and called as such:
177
+ # obj = MinStack()
178
+ # obj.push(x)
179
+ # obj.pop()
180
+ # param_3 = obj.top()
181
+ # param_4 = obj.getMin()
182
+ ```
You can’t perform that action at this time.
0 commit comments