Leetcode - Min Stack

My code:

public class MinStack {
    Stack common = new Stack();
    Stack min = new Stack();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        common.push(x);
        if (min.isEmpty() || min.peek() >= x) {
            min.push(x);
        }
    }
    
    public void pop() {
        Integer p = common.pop();
        if (p.intValue() == min.peek().intValue()) {
            min.pop();
        }
    }
    
    public int top() {
        return common.peek();
    }
    
    public int getMin() {
        return min.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();
 */

没想到这道题目我竟然从来没做过。。。
然后一开始还做错了。

其实思路很简单,就是两个栈。一个栈正规的存数字,一个栈存最小值,顶部一定是最小值。然后如果新插入的数字比他大,不用。比他小,就插。
注意,这里的比大小,
stack pop 出来的是Integer
min.peek() 也是integer, 直接用 > 比较,比较的是内存地址,得用给定的方法。

然后看答案看到了一种,只有一个stack的方法,自己写了下

My code:

public class MinStack {
    Stack st = new Stack();
    int min = Integer.MAX_VALUE;
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        if (x <= min) {
            st.push(min);
            min = x;
        }
        st.push(x);
    }
    
    public void pop() {
        int p = st.pop();
        if (p == min) {
            min = st.pop();
        }
    }
    
    public int top() {
        return st.peek();
    }
    
    public int getMin() {
        return min;
    }
}

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

reference:
https://discuss.leetcode.com/topic/41486/short-simple-java-solution-12-line

Anyway, Good luck, Richardo! -- 09/11/2016

你可能感兴趣的:(Leetcode - Min Stack)