问题描述:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
思路:
用的是一个vector来存储数字,而唯一麻烦的getMin。
首先尝试暴力解决,每次getMin都搜索一遍。结果当然是Time Limit Exceeded。
于是将Min当做一个成员存储下来,初始化为INT_MAX,有其他数的情况下INT_MAX不会是最小。
每次push,判断一下是否新加数更小;每次pop,判断一下是否把最小的数pop出去了。于是便大大减少了运行时间。
代码:
class MinStack {
private:
vector<int> my_stack;
int min;
public:
MinStack() : min(INT_MAX) {} //intialize to be the max
void push(int x) {
my_stack.push_back(x);
if (x <= min) min = x; //determine if the new one is minimun
}
void pop() {
if (my_stack.size() == 0) return;
int lasttop = top(); //record the pop number
my_stack.pop_back();
if (my_stack.size() == 0) min = INT_MAX;
else
{
int size = my_stack.size();
//if the minimun number is poped, search for the new minimun
if (min == lasttop)
{
min = my_stack[0];
for (int i = 1; i < size; i++)
{
if (my_stack[i] < min) min = my_stack[i];
}
}
}
}
int top() {
int size = my_stack.size();
if (size == 0) return -999;
return my_stack[size - 1];
}
int getMin() {
return min;
}
};
代码中包含了一些对于空容器的判断情况,只是为了避免程序错误。目测测试样例中并没有造成空容器非法操作的情况。