155-最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
辅助栈:
class MinStack {
public:
/** initialize your data structure here. */
stack<int> pool1;
stack<int> pool2;
MinStack()
{
}
void push(int x) {
if (pool1.empty())
{
pool2.push(x);
}
else
{
if (x < pool2.top())
pool2.push(x);
else
pool2.push(pool2.top());
}
pool1.push(x);
}
void pop()
{
pool1.pop();
pool2.pop();
}
int top()
{
return pool1.top();
}
int getMin()
{
return pool2.top();
}
};
空间复杂度O(1) 如何求解 注意 减法容易溢出
class MinStack {
private:
stack<long> mStack;
long min;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (mStack.empty())
{
mStack.push(0);
min = x;
}
else
{
mStack.push(x - min);
if (x < min)
min = x;
}
}
void pop()
{
if (mStack.empty())
return;
long pop = mStack.top();
if (pop < 0)
min = min - pop;
mStack.pop();
}
int top()
{
if (mStack.top() < 0)
{
return (int)min;
}
else
{
return (int)(mStack.top() + min);
}
}
int getMin()
{
return min;
}
};
push以两次 存储次最小值
class MinStack {
private:
stack<int> mStack;
int min;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (mStack.empty())
{
mStack.push(x);
min = x;
}
else
{
if (x <= min) {
mStack.push(min);
min = x;
}
mStack.push(x);
}
}
void pop() {
if (mStack.top() == min) {
mStack.pop();
if (!mStack.empty())
{
min = mStack.top();
mStack.pop();
}
}
else {
mStack.pop();
}
}
int top() {
return mStack.top();
}
int getMin() {
return min;
}
};