class MinStack {
public:
vector<int> stack;
vector<int> stmin = {INT_MAX};
void push(int x) {
if(x <= stmin[stmin.size()  1]) stmin.push_back(x);
stack.push_back(x);
}
void pop() {
if(stack[stack.size()  1] == stmin[stmin.size()  1]) stmin.pop_back();
stack.pop_back();
}
int top() {
if(stack.size() == 0) return 0;
return stack[stack.size()  1];
}
int getMin() {
return stmin[stmin.size()  1];
}
};
A 32ms C++ Solution using two vectors


One of the objects of Min Stack problem is to retrieving the minimum element in the stack, so I record the smallest element found. If x is larger than the last element in stmin vector, this x has nothing to do with with minimum value, just push into regular stack but not in minimum value stack.

When the first number pushed into the stack is a negative number, for example, 3, then getMin, the result is INT_MIN. The expected result is 3.
If you want to make INT_MIN to be the first number of stmin, add " stmin.size() == 1" in the condition judgement, aka, if (x <= stmin[stmin.size()  1]  stmin.size()  1 == 0)if (x <= stmin[stmin.size() 1]  stmin.size() 1 == 0)