a solution easy to understand, using vector.


  • 0

    import java.util.Vector;
    public class MinStack {

    public static class StackElement {
        public int value;
        public int min;
        public StackElement(int arg1, int arg2) {
            value = arg1;
            min = arg2;
        }
    }
    
    Vector<StackElement> vec = new Vector<StackElement>();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        int min = x;
        if(vec.size() > 0 && vec.get(vec.size() - 1).min < x) {
            min = vec.get(vec.size() - 1).min;
        }
        vec.add(new StackElement(x, min));
    }
    
    public void pop() {
        vec.remove(vec.size() - 1);
    }
    
    public int top() {
        return vec.get(vec.size() - 1).value;
    }
    
    public int getMin() {
        return vec.get(vec.size() - 1).min;
    }
    

    }


Log in to reply
 

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