My accepted Java solution using array list INSTEAD OF STACK


  • 0
    R

    public class MinStack {
    int tp;
    List<Integer> val;
    List<Integer> min;

    /** initialize your data structure here. */
    public MinStack() {
        tp = -1;
        val = new ArrayList<Integer>();
        min = new ArrayList<Integer>();
    }
    
    public void push(int x) {
        val.add(x);
        if(min.isEmpty()){
            min.add(x);
        }else{
            int temp = min.get(tp);
            min.add(Math.min(temp,x));
        }
        tp++;
    }
    
    public void pop() {
        if(tp>=0){
            val.remove(tp);
            min.remove(tp);
            tp--;
        }
    }
    
    public int top() {
        return val.get(tp);
        
    }
    
    public int getMin() {
        return min.get(tp);
    }
    

    }


Log in to reply
 

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