LeetCode之 面试题 栈的最小值
题目:请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
leetcode 链接:栈的最小值
思路1:使用双栈,引入辅助栈
题目要求是时间复杂度,没有要求空间复杂度。于是可以考虑引入双栈。
示例说明:主栈:mElementStack,辅助栈:mMinStack
辅助栈mElementStack存储每次push时的最小值;pop时辅助栈mMinStack和数据栈mElementStack两栈同步pop
在理解思路后,完全可以在白板上默写出来,难度不大。
public class MinStack {
//测试用例
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
int a = minStack.getMin(); //返回-3
System.out.println(a);
minStack.pop();
int b = minStack.top(); //返回 0
System.out.println(b);
int c = minStack.getMin();//返回 -2
System.out.println(c);
}
Stack<Integer> mElementStack; //用于存数据
Stack<Integer> mMinStack; //辅助栈用于存最小的值
/** initialize your data structure here. */
public MinStack() {
mElementStack = new Stack<>();
mMinStack = new Stack<>();
}
public void push(int x) {
mElementStack.push(x);
if (mMinStack.isEmpty()) {
//如果为空,则直接push
mMinStack.push(x);
} else {
//如果不为空,判断入栈的元素和辅助栈栈顶元素,谁小就push谁。
if (x > mMinStack.peek()) {
mMinStack.push(mMinStack.peek());
} else {
//当前的值小于辅助栈最顶的值时 才把当前值入栈到辅助栈
mMinStack.push(x);
}
}
}
//出栈(栈顶值删除)
public void pop() {
mElementStack.pop();
mMinStack.pop();
}
public int top() {
//peek 返回最顶的值,不改变栈的值(不删除栈顶的值),pop会把栈顶的值删除。
return mElementStack.peek();
}
public int getMin() {
return mMinStack.peek();
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
时间复杂度:O(1) 、空间复杂度:O(n)
执行结果:
思路2:用Pair数据结构来实现
class MinStack {
class Pair{
private int key;
private int value;
public Pair(int k,int v){
key=k;
value=v;
}
public int getKey(){
return key;
}
public int getValue(){
return value;
}
}
Stack<Pair> s;
/** initialize your data structure here. */
public MinStack() {
s=new Stack<>();
}
public void push(int x) {
if(s.isEmpty()){
s.push(new Pair(x,x));
}else{
s.push(new Pair(x,Math.min(x,getMin())));
}
}
public void pop() {
if(!s.isEmpty()){
s.pop();
}
}
public int top() {
return s.peek().getKey();
}
public int getMin() {
return s.peek().getValue();
}
}
思路3:优化(后期完善)
辅助无素中有冗余的数据优化思路记录,后期完善。(本篇博客立足于如何优化剑指offer的解法。)