Simple Java Solution using Java.util.stack


  • 0
    D
    class MinStack
    {
    	Stack<Data> stack;
        public MinStack()
        {
            stack = new Stack<Data>();
        }
        
        public void push(int x)
        {
            if(stack.isEmpty())
            {
            	stack.push(new Data(x,x));
            }
            else
            {
            	stack.push(new Data(x,Math.min(x, stack.peek().min)));
            }
        }
        
        public void pop()
        {
            if(!stack.isEmpty())
            {
            	stack.pop();
            }
        }
        
        public int top()
        {
            if(!stack.isEmpty())
            {
            	return stack.peek().value;
            }
            return -1;
        }
        
        public int getMin()
        {
            if(!stack.isEmpty())
            {
            	return stack.peek().min;
            }
            return Integer.MAX_VALUE;
        }
    }
    class Data
    {
    	int value;
    	int min;
    	public Data(int value, int min)
    	{
    		this.value=value;
    		this.min= min;
    	}
    }
    

Log in to reply
 

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