algorithm-base/animation-simulation/单调队列单调栈/最小栈.md

121 lines
4.5 KiB
Java
Raw Normal View History

2021-07-23 15:44:19 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
2021-03-20 11:38:55 +00:00
>
>
>
2021-07-23 15:44:19 +00:00
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-19 08:36:59 +00:00
2021-03-20 11:38:55 +00:00
#### [155. ](https://leetcode-cn.com/problems/min-stack/)
2021-03-19 08:36:59 +00:00
push pop top
- push(x) x
- pop()
- top()
- getMin()
2021-07-23 15:44:19 +00:00
> ["MinStack","push","push","push","getMin","pop","top","getMin"] > [[],[-2],[0],[-3],[],[],[],[]]
2021-03-19 08:36:59 +00:00
> [null,null,null,null,-3,null,0,-2]
####
2021-07-23 15:44:19 +00:00
pushpoptop 5123 getMin() 1
2021-03-19 08:36:59 +00:00
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/单调栈.46hlqk2xqza0.png)
B
![](https://img-blog.csdnimg.cn/20210319162722440.gif)
2021-07-23 15:44:19 +00:00
1. B
2021-03-19 08:36:59 +00:00
2. B A getMin() B
3. A B B A
####
```java
class MinStack {
//初始化
Stack<Integer> A,B;
public MinStack() {
A = new Stack<>();
B = new Stack<>();
2021-07-23 15:44:19 +00:00
}
2021-03-19 08:36:59 +00:00
//入栈,如果插入值,当前插入值小于栈顶元素,则入栈,栈顶元素保存的则为当前栈的最小元素
public void push(int x) {
A.push(x);
if (B.isEmpty() || B.peek() >= x) {
B.push(x);
}
2021-07-23 15:44:19 +00:00
}
2021-03-19 08:36:59 +00:00
//出栈如果A出栈等于B栈顶元素则说明此时栈内的最小元素改变了。
//这里需要使用 equals() 代替 == 因为 Stack 中存储的是 int 的包装类 Integer
public void pop() {
if (A.pop().equals(B.peek()) ) {
B.pop();
}
2021-07-23 15:44:19 +00:00
}
//A栈的栈顶元素
2021-03-19 08:36:59 +00:00
public int top() {
return A.peek();
}
//B栈的栈顶元素
public int getMin() {
return B.peek();
}
}
```
2021-07-27 18:26:32 +00:00
GO Code:
```go
type MinStack struct {
stack []int
minStk []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
stack: []int{},
minStk: []int{},
}
}
// Push 入栈,如果插入值,当前插入值小于栈顶元素,则入栈,栈顶元素保存的则为当前栈的最小元素
func (m *MinStack) Push(x int) {
m.stack = append(m.stack, x)
if len(m.minStk) == 0 || m.minStk[len(m.minStk) - 1] >= x {
m.minStk = append(m.minStk, x)
}
}
// Pop 出栈如果stack出栈等于minStk栈顶元素则说明此时栈内的最小元素改变了。
func (m *MinStack) Pop() {
temp := m.stack[len(m.stack) - 1]
m.stack = m.stack[: len(m.stack) - 1]
if temp == m.minStk[len(m.minStk) - 1] {
m.minStk = m.minStk[: len(m.minStk) - 1]
}
}
// Top stack的栈顶元素
func (m *MinStack) Top() int {
return m.stack[len(m.stack) - 1]
}
// GetMin minStk的栈顶元素
func (m *MinStack) GetMin() int {
return m.minStk[len(m.minStk) - 1]
}
```
2021-07-29 02:33:38 +00:00
2021-07-23 15:44:19 +00:00
###