Leetcode - Min Stack

My code:

public class MinStack {
    Stack<Integer> common = new Stack<Integer>();
    Stack<Integer> min = new Stack<Integer>();
    /** 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<Integer> st = new Stack<Integer>();
    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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/40140eb1cbc9#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞