C++ solution - single stack using std::initilaizer_list


  • 0
    G
    class MinStack {
    public:
        /** initialize your data structure here. */
        
        struct MinStruct
        {
            int X;
            int Min;
            
            MinStruct(int v)
            :
            X(v),
            Min(INT_MAX)
            {
            }
            
            MinStruct(std::initializer_list<int> l)
            :
            X(*(l.begin()))
            {
            }
        };
        
        vector<MinStruct> Stack;
        
        MinStack()
        {
        }
        
        void push(int x)
        {
            
            int MinSoFar = INT_MAX;
            
            if(Stack.empty() == false)
            {
                MinSoFar = min(MinSoFar,Stack.back().Min);        
            }
            
            Stack.push_back({x});
            Stack.back().Min = min(MinSoFar,x);
        }
        
        void pop() 
        {
            Stack.pop_back();    
        }
        
        int top() 
        {
            return Stack.back().X;    
        }
        
        int getMin() 
        {
            return Stack.back().Min;    
        }
    };

Log in to reply
 

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