C# solution: stack & minStack


  • 0
    B
    public class MinStack 
    {
    
        private Stack<int> stack = new Stack<int>();
        private Stack<int> minStack = new Stack<int>();
        public MinStack() {
            
        }
        
        public void Push(int x) 
        {
            stack.Push(x);
            
            if (minStack.Any())
            {
                var cur = minStack.Peek();
    
                if (x <= cur)
                {
                    minStack.Push(x);
                }
            }
            else
            {
                minStack.Push(x);
            }
    
        }
        
        public void Pop() {
            var cur = stack.Pop();
    
            if (minStack.Any())
            {
                if (cur == minStack.Peek())
                {
                    minStack.Pop();
                }
            }
        }
        
        public int Top() {
            return stack.Peek();
        }
    
        public int GetMin() {
    
            if (minStack.Any())   return minStack.Peek();
            return stack.Peek();
        }
    }
    

Log in to reply
 

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