155. Min Stack
做题历程:
- 2016/Oct/12, 这应该是做了不止1次了,本次耗时14分钟,独立解出
如果第一次做这道题的话,其实挺难直接解出的,我觉得这题应该算成Medium比较合适。。 大概说下思路吧:
- 用两个
stack<int>来存储,其中一个是标准的stack,就是正常存东西,另外一个就是所谓的Min Stack,只有在x小于等于min_stack.top()的时候,才插入到min_stack中。。。这个的正确性需要仔细想一想。。。
代码如下:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
// empty constructor
}
void push(int x) {
st_stack.push(x);
if (min_stack.empty() || min_stack.top() >= x) {
min_stack.push(x);
}
}
void pop() {
if (!min_stack.empty() && st_stack.top() == min_stack.top()) {
min_stack.pop();
}
st_stack.pop();
}
int top() {
return st_stack.top();
}
int getMin() {
return min_stack.top();
}
private:
stack<int> st_stack;
stack<int> min_stack;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/