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


  • 0
    R

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

    class MinStack {
    private:
        vector<int> stack;
        int min = NULL;
    public:
    
    /** initialize your data structure here. */
    
    void push(int x) {
        if (stack.empty()) min = x;
        stack.push_back(x-min);
        min = min < x ? min: x;
    }
    
    void pop() {
        if (stack.empty()) return;
        if (stack.back() < 0) min = min - stack.back();
        stack.pop_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
    Z

    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.