Home > AI > Data Structure > Stack >

leetcode-155-Min Stack

Solution (Java)

class MinStack {

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

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

This method is not space efficient since it stores many duplicate min values.

Leave a Reply