题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
题目地址
思路
- 因为要求在常数时间内完成所有操作,所以不能有排序操作
- 使用一个辅助栈保存最小、次小、…
Code
class Solution {
stack<int> s;
stack<int> s_min;
public:
void push(int value) {
s.push(value);
if (s_min.empty())
s_min.push(value);
if (value <= s_min.top()) // 注意是小于等于
s_min.push(value);
}
void pop() {
if (s.top() == s_min.top())
s_min.pop();
s.pop();
}
int top() {
return s.top();
}
int min() {
return s_min.top();
}
};