C++ solution uses one vector right on Xcode but can submit

  • 0

    Could any tell me why this is wrong? I tested it on Xcode and it passed.

    class MinStack {
        vector<int> stack;
        int min = NULL;
    /** initialize your data structure here. */
    void push(int x) {
        if (stack.empty()) min = x;
        min = min < x ? min: x;
    void pop() {
        if (stack.empty()) return;
        if (stack.back() < 0) min = min - stack.back();
    int top() {
        if (stack.empty()) return NULL;
        return stack.back() > 0 ? min + stack.back() : min;
    int getMin() {
        if (stack.empty()) return NULL;
        return min;

  • 0

    The pop() function is wrong. If the minimum is the last element and you pop it, then what is the new minimum number? Definitely it is not (min = min - stack.back();)

Log in to reply

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