min、push、pop的复杂度均为O(1)。
分析:
1)对于push操作, 需要考虑栈是否已满;对于pop操作,需要考虑栈是否为空。当栈满和栈空的时候push或pop操作是不成功的,需要给出提示。因此可以设计出如下的函数。
bool push(int) 和bool pop(int&)
2)对于min操作,需要考虑
a) 栈为空,此时,min操作无效
b) 如果在push和pop的时候更新,由于栈中可能存在相等的数,pop的时候最小值还不一定会改变。由于题目要求用栈实现,如果额外使用一个最小堆的话不符合要求。一种简单的方法是push的时候,同时将最小值push进去。此时空间复杂度为2n
代码:
#include <iostream>
using namespace std;
struct StackElement
{
int ele;
int min;
StackElement(int e, int m) {
ele = e;
min = m;
}
StackElement(){}
};
class Stack
{
public:
Stack() {
count = 0;
}
bool push(int);
bool pop(int&);
bool min(int&);
private:
static const int STACK_SIZE = 100;
StackElement elements[STACK_SIZE];
int count;
};
bool Stack::push(int num)
{
if(count < STACK_SIZE) {
int min = elements[count-1].min;
if(min > num) min = num;
elements[count].ele = num;
elements[count].min = min;
count ++;
return true;
}
return false;
}
bool Stack::pop(int& num) {
if(count > 0) {
count --;
num = elements[count].ele;
return true;
}
return false;
}
bool Stack::min(int& num) {
if(count > 0){
num = elements[count-1].min;
return true;
}
return false;
}
void test() {
Stack stack;
stack.push(3);
stack.push(1);
stack.push(2);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
int min, top;
while(stack.min(min)) {
stack.pop(top);
cout << "min=" << min << ", then pop " << top << endl;
}
}
int main()
{
test();
return 0;
}