题目链接:https://oj.leetcode.com/problems/min-stack/
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
分析:题目要求设计一个栈可以在常数时间内执行push,pop,top以及得到最小值min的操作。
算法一:建立一个结构体,其中一个域值为x,另一个域值为栈中的最小值。因此就可以在O(1)的时间内获得整个栈的最小值。但是这种算法的结果是:Memory limit exceed.
算法二:建立另外一个栈s2,栈顶元素为s1当前所有元素的最小值。
算法一代码:
#include<iostream>
#include<stack>
using namespace std;
class MinStack
{
private:
typedef struct Node
{
int val;
int min_temp;
}tNode;
stack<tNode> s;
public:
void push(int x)
{
tNode n;
n.val = x;
if( s.empty() )
{
n.min_temp = x;
}
else
{
if( x < s.top().min_temp )
{
n.min_temp = x;
}
else
{
n.min_temp = s.top().min_temp;
}
}
s.push(n);
}
void pop()
{
s.pop();
}
int top()
{
return s.top().val;
}
int getMin()
{
return s.top().min_temp;
}
};
int main()
{
MinStack ms;
ms.push(1);
ms.push(2);
ms.push(3);
ms.push(4);
ms.push(5);
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
system("pause");
return 0;
}<strong>
</strong>
结果是:memory limit exceed. 究其原因就是因为min_temp域占用了过多的空间,因为每一个元素都会保存最小值,这是完全没有必要的。
算法二的AC+完整代码:
#include<iostream>
#include<stack>
using namespace std;
class MinStack
{
private:
stack<int> s1;
stack<int> s2;
public:
void push(int x)
{
s1.push(x);
if( s2.empty() )
{
s2.push(x);
}
else if( x <= s2.top() )
{
s2.push(x);
}
}
void pop()
{
int top = s1.top();
s1.pop();
if( top<=s2.top() )
{
s2.pop();
}
}
int top()
{
return s1.top();
}
int getMin()
{
return s2.top();
}
};
int main()
{
MinStack ms;
ms.push(1);
ms.push(2);
ms.push(3);
ms.push(4);
ms.push(5);
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
cout<<"top = "<<ms.top()<<" min = "<<ms.getMin()<<endl;
ms.pop();
system("pause");
return 0;
}
原文地址:http://blog.csdn.net/lavorange/article/details/41981861