c++ using two stacks (O(1))


  • 1
    class MinStack {
    public:
      stack<int> elements;
      stack<int> min_elem;
      MinStack() {}
    
      void push(int x) {
        elements.push(x);
        if (min_elem.empty() || x <= min_elem.top())
          min_elem.push(x);
      }
    
      void pop() {
        if (elements.top() == min_elem.top())
          min_elem.pop();
        elements.pop();
      }
    
      int top() {
        if (elements.empty()) return 0;
        else return elements.top();
      }
    
      int getMin() {
        if (min_elem.empty()) return 0;
        else return min_elem.top();
      }
    };
    
    

Log in to reply
 

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