题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
在线链接
代码:
import java.util.Stack;
public class Solution {
Stack<Integer> st1 = new Stack<>();
Stack<Integer> st2 = new Stack<>();
public void push(int node) {
st1.push(node);
if(st2.isEmpty() || st2.peek() > node){
st2.push(node);
}else {
st2.push(st2.peek());
}
}
public void pop() {
st1.pop();
st2.pop();
}
public int top() {
return st1.peek();
}
public int min() {
return st2.peek();
}
}
思路概述:
使用两个栈,st1正常的进出栈,进栈时,如果st2为空或者st2栈顶元素大于进栈元素,才正常添加元素,否则,再添加一份栈顶元素,这样可以保证st2存的都是st1当前存储元素的最小值