
public class Solution {
private Stack<Integer> s1 = new Stack();
private Stack<Integer> s2 = new Stack();
public void push(int node) {
s1.push(node);
if(s2.isEmpty()){
s2.push(node);
}else{
s2.push(Math.min(s2.peek(),node));
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}
这个博客展示了如何使用两个栈实现一个数据结构,该结构支持常规的栈操作(push, pop, top)以及返回栈中当前的最小元素。在push操作中,最小元素栈会保存当前的最小值。在min操作中,可以快速获取最小值。这个设计有效地避免了在每次操作时遍历整个栈来查找最小元素,提高了效率。
746

被折叠的 条评论
为什么被折叠?



