Retrieving the Min element in a stack in O(1) Time

后端 未结 3 1034
一生所求
一生所求 2021-02-06 09:33

The reason I\'m asking this question is because I cannot see why the way I think cannot be applied to this particular question

\"How would you design a stack which,

3条回答
  •  独厮守ぢ
    2021-02-06 10:03

    I found this solution here

    struct StackGetMin {
      void push(int x) {
        elements.push(x);
        if (minStack.empty() || x <= minStack.top())
          minStack.push(x);
      }
      bool pop() {
        if (elements.empty()) return false;
        if (elements.top() == minStack.top())
          minStack.pop();
        elements.pop();
        return true;
      }
      bool getMin(int &min) {
        if (minStack.empty()) {
          return false;
        } else {
          min = minStack.top();
          return true;
        }
      }
      stack elements;
      stack minStack;
    };
    

提交回复
热议问题