试题链接:https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tPage=1
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
class Solution {
private:
stack<int> st, minst;
public:
void push(int value) {
st.push(value);
if(minst.empty()){ //先要考虑第一次加入到minst的时候,不然报错
minst.push(value);
}else{
if(st.top() <= minst.top()){ //将小的数加入到最小栈中
minst.push(st.top());
}
}
}
void pop() {
if(st.top() == minst.top()){ //因为会不断加入新的节点,当新的节点比之前的小,但是被pop了以后那么原来大的节点又变成了最小节点,所以在这里进行一次判断。
minst.pop();
}
st.pop();
}
int top() {
return st.top();
}
int min() {
return minst.top();
}
};