【剑指offer】包含min函数的栈 --Java实现
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))
解题思路
双栈法,使用辅助栈,其中一个栈total用来存储所有的元素,另一个min用来存储添加新元素后total对应的最小值
1、如果新元素小于等于min的栈顶元素,就压入min的栈顶
2、否则,压入min当前的栈顶元素
核心代码
import java.util.Stack; public class Solution { Stack<Integer> total = new Stack<Integer>(); Stack<Integer> min = new Stack<Integer>(); public void push(int node) { total.push(node); if(min.empty()){ min.push(node); }else{ if(node<=min.peek()){ min.push(node); }else{ min.push(min.peek()); } } } public void pop() { total.pop(); min.pop(); } public int top() { return total.peek(); } public int min() { return min.peek(); } }
浙公网安备 33010602011771号