Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 20c5079

Browse files
ybian19azl397985856
authored andcommitted
feat: 155.min-stack add Python3 implementation (azl397985856#97)
1 parent 21350e7 commit 20c5079

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

‎problems/155.min-stack.md‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ top也是直接返回栈顶元素即可。 这种做法每次修改栈都需要
3030

3131
![155.min-stack](../assets/problems/155.min-stack-1.png)
3232

33-
是否有更高效的算法呢?答案是有的。
33+
是否有更高效的算法呢?答案是有的。
3434

3535
我们每次入栈的时候,保存的不再是真正的数字,而是它与当前最小值的差(当前元素没有入栈的时候的最小值)。
3636
这样我们pop和top的时候拿到栈顶元素再加上**上一个**最小值即可。
@@ -60,6 +60,10 @@ pop或者top的时候:
6060

6161
## 代码
6262

63+
* 语言支持:JS,Python
64+
65+
Javascript Code:
66+
6367
```js
6468
/*
6569
* @lc app=leetcode id=155 lang=javascript
@@ -131,3 +135,48 @@ MinStack.prototype.getMin = function() {
131135
*/
132136
```
133137

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+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /