最小栈 (最小栈)

 

思路:通过peek方法

// @Title: 最小栈 (最小栈)
// @Author: qisiii
// @Date: 2022-02-21 10:59:31
// @Runtime: 13 ms
// @Memory: 43.3 MB
// @comment: 通过peek方法
// @flag: BLUE
class MinStack {
    private Stack<Integer> store=new Stack();
    private Stack<Integer> min=new Stack();
    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int x) {
        store.push(Integer.valueOf(x));
        if(min.isEmpty()||min.peek()>=x){
            min.push(Integer.valueOf(x));
        }
    }
    
    public void pop() {
        if(store.peek().equals(min.peek())){
            min.pop();
        }
        store.pop();
    }
    
    public int top() {
        Integer value=store.peek();
        return value==null?0:value.intValue();
    }
    
    public int min() {
        Integer value=min.peek();
        return value==null?0:value.intValue();
    }
}

/**
 * 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.min();
 */

思路:不知道有peek方法

// @Title: 最小栈 (最小栈)
// @Author: qisiii
// @Date: 2022-02-21 10:55:00
// @Runtime: 14 ms
// @Memory: 43.1 MB
// @comment: 不知道有peek方法
// @flag: BLUE
class MinStack {
    private Stack<Integer> store=new Stack();
    private Stack<Integer> min=new Stack();
    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int x) {
        store.push(Integer.valueOf(x));
        if(min.isEmpty()){
            min.push(Integer.valueOf(x));
        }else {
            Integer pop = min.pop();
            min.push(pop);
            if (pop>=x){
                min.push(x);
            }
        }
    }
    
    public void pop() {
        Integer pop = store.pop();
        Integer minpop = min.pop();
        if (!pop.equals(minpop)){
            min.push(minpop);
        }
    }
    
    public int top() {
        Integer value=store.pop();
        if (value!=null){
            store.push(value);
            return value.intValue();
        }
        return 0;
    }
    
    public int min() {
        Integer value=min.pop();
        if (value!=null){
            min.push(value);
            return value.intValue();
        }
        return 0;
    }
}

/**
 * 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.min();
 */
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18