要求实现一个时间复杂度O(1)的函数,找到栈中的最小值。
那么以空间换时间,加入一个辅助栈即可。
package 剑指Offer.栈.包含min函数的栈;
import java.util.Stack;
/**
* @program:多线程和IO
* @descripton:辅助栈实现
* @author:ZhengCheng
* @create:2021/10/29-19:57
**/
public class minStack {
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> mStack = new Stack<>();
public void push(int val){
stack.push(val);
if (!mStack.isEmpty()){
if (val < mStack.peek()){
mStack.push(val);
}
}else {
mStack.push(val);
}
}
public int min(){
return mStack.peek();
}
public int pop (){
if (stack.peek() == mStack.peek()){
mStack.pop();
}
return stack.pop();
}
}