Min Stack leetcode

时间:2023-03-08 23:42:46
Min Stack leetcode

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();
min = x;
}
else
{
sta.push(x - min);
if (x < min)
min = x;
}
} void pop() {
if (sta.empty())
return;
long top = sta.top();
if (top < )
min = min - top;
sta.pop();
} int top() {
if (sta.empty())
return ;
long top = sta.top();
if (top < )
return min;
else
return min + top;
} int getMin() {
return min;
}
private:
stack<long> sta;
long min;
};