MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.
public class MinStack {
    Stack<Integer> stk;
    int min;
    
    /** initialize your data structure here. */
    public MinStack() {
        stk = new Stack<Integer>();
        min = Integer.MAX_VALUE;
    }
    
    public void push(int x) {
        if(x <= min){
            stk.push(min);
            min = x;
        }
        stk.push(x);
    }
    
    public void pop() {
        if(stk.peek() == min){
            stk.pop();
            min = stk.pop();
        } else {
            stk.pop();
        }
    }
    
    public int top() {
        return stk.peek();
    }
    
    public int getMin() {
        return min;
    }
}
public class MinStack {
    ArrayDeque<Integer> stack, min;
    
    public MinStack() {
        this.stack = new ArrayDeque<Integer>();
        this.min = new ArrayDeque<Integer>();
    }
    
    public void push(int x) {
        stack.push(x);
        if(min.isEmpty() || x <= min.peek()){
            min.push(x);
        }
    }
    
    public void pop() {
        if(stack.isEmpty()){
            return; 
        }
        if(min.peek().equals(stack.peek())){
            min.pop();
        }
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min.peek();
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。


« 上一篇
word break
下一篇 »
merge Interval