/** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */
O(1) Extra Space
The stack does not record the value, but records the offset from the minimum value, and uses another number to store the minimum value
classMinStack { private: // Record the offset from the minimum value stack<long> st; long min_val;
public: MinStack() { }
voidpush(int val) { if (st.empty()) { st.push(0); min_val = val; } else { long diff = val - min_val; st.push(diff);
if (diff < 0) // If the current top value is less than min_val, update the minimum value min_val = val; } }
voidpop() { long diff = st.top(); st.pop();
if (diff < 0) min_val = min_val - diff; // Restore the previous minimum value }
inttop() { long offset = st.top(); if (offset <= 0) // Indicates that the current top of the stack is exactly the minimum value return (int)min_val; else return (int)(min_val + offset); }
intgetMin() { return (int)min_val; } };
/** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */
LeetCode Hot 100 rewrite, although it took some time, I still wrote it myself. Summarize two error-prone points:
Use long instead of int, because-2^31 <= val <= 2^31 - 1
When the current top of the stack is negative, top() should return min_val
if (stk.empty()) { min_val = input_val; stk.push(0); return; }
stk.push(input_val - min_val);
if (val < min_val) min_val = input_val; } // pop, top, and getMin operations are always called on a non-empty stack voidpop() { long top_val = stk.top();