Java solution with only one ArrayList


  • -1
    S

    public class MinStack {
    int min;
    ArrayList<Integer> list;

    MinStack(){
    	min=Integer.MAX_VALUE;                             
    	list=new ArrayList<Integer>();
    }
    
    public void push(int x) {
        list.add(x);
        if(x<min){
        	min=x;
        }
    }
    
    public void pop() {
        if(list.isEmpty())
        	return;        
        if(list.get(list.size()-1)==min){
        	min=Integer.MAX_VALUE;
        	for(int i=0;i<list.size()-1;i++){
        		if(list.get(i)<min)
        			min=list.get(i);
        	}
        }
        list.remove(list.size()-1);
    }
    
    public int top() {
        return list.get(list.size()-1);
    }
    
    public int getMin() {
        return min;
    }
    

    }


  • 0
    S

    lol is this pop operation O(1) ?


Log in to reply
 

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