零、题目描述
一、在LeetCode中Java实现
class MinStack {
/** initialize your data structure here. */
public MinStack() { }
/*
* 使用Java中的Stack类创建两个stack对象
* stack1:用于存储题目中待存储的数据
* stack2:用于存储stack1中的最小值
*/
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
/*
* push()方法
* stack1:入栈
* stack2:空:直接入栈
* 非空:stack1中入栈元素和stack2栈顶元素比较,小的一方入栈stack2
*/
public void push(int x) {
stack1.push(x);
if(stack2.isEmpty())
stack2.push(x);
else {
if(x < stack2.peek())
stack2.push(x);
else
stack2.push(stack2.peek());
}
}
// stack1和stack2都出栈
public void pop() {
stack1.pop();
stack2.pop();
}
// 获取stack1栈顶元素
public int top() {
return stack1.peek();
}
/*
* 获取stack1中的最小值
* 即stack2中的栈顶元素
*/
public int getMin() {
return stack2.peek();
}
}
二、在eclipse中测试
public class Test {
public static void main(String[] args) {
MinStack_155 min = new MinStack_155();
min.push(-4);
min.push(0);
min.push(-5);
System.out.println(min.getMin());
min.pop();
System.out.println(min.getMin());
}
}
测试结果
-5
-4
三、解题思路
- 由题目知道这题通过栈来实现
- 主要难点在于时间复杂度为O(1)
- 所以不能够通过遍历来寻找最小值
- 所以可以在入栈时使用另一个栈来存储最小值
四、LeetCode精选题解
最小栈精选题解
辅助栈可以在只有更小的元素入栈时同步入栈,最小元素出栈时同步出栈,可以减少辅助栈的大小。
此解法来自LeetCode,liweiwei1419用户
import java.util.Stack;
public class MinStack {
// 数据栈
private Stack<Integer> data;
// 辅助栈
private Stack<Integer> helper;
/**
* initialize your data structure here.
*/
public MinStack() {
data = new Stack<>();
helper = new Stack<>();
}
// 思路 2:辅助栈和数据栈不同步
// 关键 1:辅助栈的元素空的时候,必须放入新进来的数
// 关键 2:新来的数小于或者等于辅助栈栈顶元素的时候,才放入(特别注意这里等于要考虑进去)
// 关键 3:出栈的时候,辅助栈的栈顶元素等于数据栈的栈顶元素,才出栈,即"出栈保持同步"就可以了
public void push(int x) {
// 辅助栈在必要的时候才增加
data.add(x);
// 关键 1 和 关键 2
if (helper.isEmpty() || helper.peek() >= x) {
helper.add(x);
}
}
public void pop() {
// 关键 3:data 一定得 pop()
if (!data.isEmpty()) {
// 注意:声明成 int 类型,这里完成了自动拆箱,从 Integer 转成了 int,因此下面的比较可以使用 "==" 运算符
// 参考资料:https://www.cnblogs.com/GuoYaxiang/p/6931264.html
// 如果把 top 变量声明成 Integer 类型,下面的比较就得使用 equals 方法
int top = data.pop();
if(top == helper.peek()){
helper.pop();
}
}
}
public int top() {
if(!data.isEmpty()){
return data.peek();
}
throw new RuntimeException("栈中元素为空,此操作非法");
}
public int getMin() {
if(!helper.isEmpty()){
return helper.peek();
}
throw new RuntimeException("栈中元素为空,此操作非法");
}
}