题目摘要
实现一个栈,支持push, pop, top, getMin等方法
- 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.
解法
1. 用两个java栈stack和minStack,stack正常保存数, minStack保存不大于顶部元素的数
2. 只用一个栈,和一个最小值min,栈里面保存入栈数和最小值的差值,最小值随时更新,没有具体实现
注意
1. pop()时注意判空
2. 注意euqals()
和==
的区别
原题
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.