定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
建立一个temp用来存储对应的最小值。
当push的值小于等于temp.top时,放入temp中。
当pop的值等于temp.top时,temp也pop。
class MinStack {
public:
stack<int> temp;//保存最小值用
stack<int> ans;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
ans.push(x);
if(temp.empty()||x<=temp.top())
temp.push(x);
}
void pop() {
if(ans.top()==temp.top())
temp.pop();
ans.pop();
}
int top() {
return ans.top();
}
int min() {
return temp.top();
}
};
/**
* 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->min();
*/
京公网安备 11010502036488号