您的位置:首页 > 其它

剑指off-O(1)得到栈的最小元素

2015-07-19 15:50 176 查看
题目:实现一个栈,要求可以得到min,pop
push min 复杂度O(1) min是得到最小元素,不是得到最小并弹出来
分析:用一个辅助栈,每次push的时候都是压入最小的元素,同时弹出
偷懒了,用STL的栈简单写一下
<span style="font-size:14px;">void push(stack<int > &stack1,stack<int > &stack2,int n)
{
if (stack1.empty()) {
stack1.push(n);
stack2.push(n);
}
else
{
stack1.push(n);
int temp= stack2.top();
if (n<temp) {
stack2.push(n);
}
else
stack2.push(temp);
}
}
void pop(stack<int > &stack1,stack<int > &stack2)
{
if (!stack1.empty()) {
printf("the stack is empty");
return ;
}
stack1.pop();
stack2.pop();
}
int min(stack<int > &stack2)
{
return stack2.top();
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: