传送带:剑指 Offer 30. 包含min函数的栈 - 力扣(LeetCode)
问题
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
思路
开一个辅助栈存储每次push进来后当前的minNum
代码(感谢批评指正emm)
class MinStack {
stack<int> stk;
stack<int> minNum;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
stk.push(x);
if(minNum.size() == 0){
minNum.push(x);
}
else{
if(x > minNum.top())
minNum.push(minNum.top());
else{
minNum.push(x);
}
}
}
void pop() {
stk.pop();
minNum.pop();
}
int top() {
return stk.top();
}
int min() {
return minNum.top();
}
};