The problem for the solution is the cast. Since the possible gap between the current value and the min value could be Integer.MAX_VALUE-Integer.MIN_VALUE;
You can't compare twoIntegerwith a simple == they're objects so most of the time references won't be the same.
There is a trick, with Integer between -128 and 127, references will be the same as autoboxing usesInteger.valueOf()which caches small integers.
因此,可以先用int强制转化。
参考:
// "static void main" must be defined in a public class.publicclassMain {publicstaticvoidmain(String[] args) {Stack<Integer> s =newStack<>();Stack<Integer> t =newStack<>();s.push(-1);t.push(-1);System.out.println(s.pop() ==t.pop());s.push(-129);t.push(-129);System.out.println(s.pop() ==t.pop());s.push(128);t.push(128);System.out.println(s.pop() ==t.pop()); }}// output:// true// false// false
--
Time: O(1)
Space: O(n)
classMinStack {Stack<Integer> stack;Stack<Integer> minStack; /** initialize your data structure here. */publicMinStack() { stack =newStack<Integer>(); minStack =newStack<Integer>(); }publicvoidpush(int x) {stack.push(x);if (minStack.isEmpty()) {minStack.push(x); }elseif ((int) minStack.peek() >= x) {minStack.push(x); } }publicvoidpop() {int x =stack.pop();if (!minStack.isEmpty() && x ==minStack.peek()) {minStack.pop(); } }publicinttop() {returnstack.peek(); }publicintgetMin() {returnminStack.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(); */
Using One Stack - store difference between x and min
Time: O(1)
Space: O(1)
top() - 如果当前栈顶的对应元素是新的min值,那么 top() 对应 min, 否则对应 stack.peek() + min