时间复杂度: O ( 1 ) O(1) O(1)
空间复杂度: O ( n ) O(n) O(n)
class MinStack {
private Stack stack;
class Node
{
int x;
int min;
public Node(int x, int min)
{
super();
this.x = x;
this.min = min;
}
}
public MinStack()
{
stack = new Stack<>();
}
public void push(int x)
{
if (stack.isEmpty())
stack.add(new Node(x, x));
else
stack.add(new Node(x, Math.min(x, stack.peek().min)));
}
public void pop()
{
stack.pop();
}
public int top()
{
return stack.peek().x;
}
public int getMin()
{
return stack.peek().min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/