C# Solution


  • 0
    M
    public class MinStack {
    /** initialize your data structure here. */
    int min;
    Stack<int> stack; 
    public MinStack() {
        stack = new Stack<int>(); 
        min = int.MaxValue; 
    }
    
    public void Push(int x) {
        stack.Push(x);
        if (x < min) min = x; 
    }
    
    public void Pop() {
        if (stack.Count == 0) return; 
        
        int val = stack.Pop(); 
        if (val == min)
        {
            min = int.MaxValue; 
            Stack<int> tempStack = new Stack<int>(); 
            
            while (stack.Count > 0)
            {
                int temp = stack.Peek(); 
                if (temp < min) min = temp; 
                tempStack.Push(stack.Pop());
            }
            
            while (tempStack.Count > 0)
            {
                stack.Push(tempStack.Pop());
            }
        }
    }
    
    public int Top() {
        return stack.Peek(); 
    }
    
    public int GetMin() {
        return min; 
    }
    }

Log in to reply
 

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