#LeetCode 155 (#剑指offer 30)
Problem Description
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.


class MinStack {
public:
//Create two empty stacks.
stack<int> c;
stack<int> m; //Min stack;
void push(int val) {
//When min stack is empty or val less and equal the top element
//Equal condition can avoid val be push more time.
//At first,i don't write equal condition,it waste me more time
if (m.empty() || val <= getMin())
m.push(val); //push val into min stack
c.push(val);
}
void pop() {
if (c.top() == getMin())
m.pop(); //Update the min stack top element.
c.pop();
}
int top() {
return c.top();
}
int getMin() {
return m.top();
}
};
Wish this toturial can help you!
让思维见见世面
浙公网安备 33010602011771号