2019-11-02 12:07:41 +08:00
|
|
|
|
# 30. 包含 min 函数的栈
|
|
|
|
|
|
2020-11-04 01:40:59 +08:00
|
|
|
|
## 题目链接
|
|
|
|
|
|
|
|
|
|
[牛客网](https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
2020-11-04 01:40:59 +08:00
|
|
|
|
实现一个包含 min() 函数的栈,该方法返回当前栈中最小的值。
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
2020-11-04 01:40:59 +08:00
|
|
|
|
使用一个额外的 minStack,栈顶元素为当前栈中最小的值。在对栈进行 push 入栈和 pop 出栈操作时,同样需要对 minStack 进行入栈出栈操作,从而使 minStack 栈顶元素一直为当前栈中最小的值。在进行 push 操作时,需要比较入栈元素和当前栈中最小值,将值较小的元素 push 到 minStack 中。
|
|
|
|
|
|
2020-11-04 02:14:47 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20201104013936126.png" width="350px"> </div><br>
|
2020-11-04 01:40:59 +08:00
|
|
|
|
|
2019-11-02 12:07:41 +08:00
|
|
|
|
```java
|
|
|
|
|
private Stack<Integer> dataStack = new Stack<>();
|
|
|
|
|
private Stack<Integer> minStack = new Stack<>();
|
|
|
|
|
|
|
|
|
|
public void push(int node) {
|
|
|
|
|
dataStack.push(node);
|
|
|
|
|
minStack.push(minStack.isEmpty() ? node : Math.min(minStack.peek(), node));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void pop() {
|
|
|
|
|
dataStack.pop();
|
|
|
|
|
minStack.pop();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public int top() {
|
|
|
|
|
return dataStack.peek();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public int min() {
|
|
|
|
|
return minStack.peek();
|
|
|
|
|
}
|
|
|
|
|
```
|
2019-11-02 14:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|