定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
class Solution {
stack<int> s;
public:
void push(int value) {
s.push(value);
}
void pop() {
if(s.empty()) return ;
s.pop();
}
int top() {
return s.top();
}
int min() {
stack<int> temp;
int min = s.top();
while(!s.empty()){ //取最小元素
if(min>s.top())
min = s.top();
temp.push(s.top());
s.pop();
}
while(!temp.empty()) //把栈中的所有元素都归还给原有栈
{
s.push(temp.top());
temp.pop();
}
return min;
}
};