您的位置:首页 > 其它

Min Stack leetcode

2016-01-03 21:32 435 查看
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.

使用一个栈,和一个保存最小值的变量min

栈中保存的元素是 新加数和当前min的差,然后更新min,使min保持最小

利用差值使每个栈元素可以包含两个信息量

class MinStack {
public:
void push(int x) {
if (sta.empty())
{
sta.push(0);
min = x;
}
else
{
sta.push(x - min);
if (x < min)
min = x;
}
}

void pop() {
if (sta.empty())
return;
long top = sta.top();
if (top < 0)
min = min - top;
sta.pop();
}

int top() {
if (sta.empty())
return 0;
long top = sta.top();
if (top < 0)
return min;
else
return min + top;
}

int getMin() {
return min;
}
private:
stack<long> sta;
long min;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: