先将首元素推入栈中,新加入的元素如果大于栈顶元素就不处理,新加入的元素如果小于等于栈顶元素就将新元素入栈。
class MinStack {
/** initialize your data structure here. */
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack()
{
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x)
{
stack.push(x);
if (!minStack.isEmpty())
{
int top = minStack.peek();
if (x <= top)
minStack.push(x);
}
else
minStack.push(x);
}
public void pop()
{
int pop = stack.pop();
int top = minStack.peek();
if (pop == top)
minStack.pop();
}
public int top()
{
return stack.peek();
}
public int getMin()
{
return minStack.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
* /