My java solution with class and one stack.


  • 0
    J
    class element{
        int value;
        int min;
        public element(int value, int min){
            this.value = value;
            this.min = min;
        }
    }
    
    int min = Integer.MAX_VALUE;
    Stack<element> st = new Stack<element>();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        if(min > x)
            min = x;
        
        st.push(new element(x, min));
    }
    
    public void pop() {
        st.pop();
        if(!st.isEmpty())
            min = st.peek().min;
        else
            min = Integer.MAX_VALUE;
    }
    
    public int top() {
        element elem = st.peek();
        return elem.value;
    }
    
    public int getMin() {
        element elem = st.peek();
        return elem.min;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.