[LeetCode] #155 最小栈

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。

pop() —— 删除栈顶的元素。

top() —— 获取栈顶元素。

getMin() —— 检索栈中的最小元素。

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2

双栈法

class MinStack {

    private Stack<Integer> xStack;
    private Stack<Integer> minStack;

    /** initialize your data structure here. */
    public MinStack() {
        xStack = new Stack<Integer>();
        minStack = new Stack<Integer>();
        minStack.push(Integer.MAX_VALUE);
    }
    
    public void push(int val) {
        xStack.push(val);
        minStack.push(Math.min(minStack.peek(), val));
    }
    
    public void pop() {
        xStack.pop();
        minStack.pop();
    }
    
    public int top() {
        return xStack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

单栈法

class MinStack {

    private Stack<Integer> stack;

    /** initialize your data structure here. */
    public MinStack() {
       stack = new Stack<>();
    }
    
    public void push(int val) {
      if(stack.isEmpty()){
        stack.push(val);
        stack.push(val);
    }
else{ int tmp = stack.peek(); stack.push(val); if(tmp<val){ stack.push(tmp); }else{ stack.push(val); }
    } }
public void pop() { stack.pop(); stack.pop(); } public int top() { return stack.get(stack.size()-2); } public int getMin() { return stack.peek(); } }

知识点:

总结:

posted @ 2021-08-18 20:39  1243741754  阅读(24)  评论(0编辑  收藏  举报