题目:
设计一个包含min函数的栈,得到最小元素,其中要求push,pop,min时间复杂度均为O(1).
思路:
采用空间换时间,引进一个辅助数组,存储当前所有元素中最小元素的下标,每次往栈中压入新的元素时更新此数组.
代码如下:
#include <iostream>
using namespace std;
typedef int Elemtype;
class MinStack
{
public:
MinStack(int defaultSize=1000);
~MinStack() { delete [] data; delete []Index;}
void Push(Elemtype key);
void Pop(Elemtype &key);
Elemtype GetMin();
private:
Elemtype *data;
int *Index;
int top;
int maxSize;
};
MinStack::MinStack(int defaultSize)
{
maxSize=defaultSize;
data=new Elemtype[maxSize];
Index=new int[maxSize];
top=-1;
}
void MinStack::Push(Elemtype key)
{
data[++top]=key;
if(top==0)
Index[top]=0;
else if(key<=data[Index[top-1]]) //更新在当前元素下最小元素的下标
Index[top]=top;
else if(key>data[Index[top-1]])
Index[top]=Index[top-1];
}
void MinStack::Pop(Elemtype &key)
{
if(top<0)
return ;
key=data[top];
top--;
}
int MinStack::GetMin()
{
if(top>=0)
return data[Index[top]];
}
int main()
{
MinStack s;
Elemtype key;
int a[5]={5,3,2,6,1};
for(int k=0;k<5;++k)
s.Push(a[k]);
cout<<"最小值为"<<s.GetMin()<<endl;
s.Pop(key);
cout<<key<<endl;
cout<<s.GetMin()<<endl;
system("pause");
}