目录
[0302. 栈的最小值](#0302. 栈的最小值)
0302. 栈的最小值
题目描述:
请设计一个栈,除了常规栈支持的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.实现代码与解析:
栈
            
            
              java
              
              
            
          
          //请设计一个栈,除了常规栈支持的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. 
//
// Related Topics 栈 设计 👍 102 👎 0
import java.util.Stack;
//leetcode submit region begin(Prohibit modification and deletion)
class MinStack {
    Stack<Integer> stk1 = new Stack();
    Stack<Integer> stk2 = new Stack();
    /** initialize your data structure here. */
    public MinStack() {
        stk1 = new Stack();
        stk2 = new Stack();
        stk2.push(Integer.MAX_VALUE);
    }
    
    public void push(int x) {
        stk1.push(x);
        stk2.push(Math.min(stk2.peek(), x));
    }
    
    public void pop() {
        stk1.pop();
        stk2.pop();
    }
    
    public int top() {
        Integer peek = stk1.peek();
        return peek;
    }
    
    public int getMin() {
        Integer peek = stk2.peek();
        return 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();
 */
//leetcode submit region end(Prohibit modification and deletion)原理思路:
简单题,定义一个辅助栈,记录每个状态的最小值即可。