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.
Example:
MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin(); --> Returns -3.minStack.pop();minStack.top(); --> Returns 0.minStack.getMin(); --> Returns -2.
这里本来以为用上stack类,可以轻而易举的实现,当然我还可以使用其他的队列实现。只是getMin要特殊处理一下,毕竟statck就只有那几个方法,会比较麻烦一点,但是看到别的大神是那么写的,智商抓急,这样写的确比较方便,就是如果想看size会比较奇怪!