Implement a stack with following functions:
push(val)
push val into the stackpop()
pop the top element and return itmin()
return the smallest number in the stackAll above should be in O(1) cost.
Example 1:
Input:
push(1)
pop()
push(2)
push(3)
min()
push(1)
min()
Output:
1
2
1
Notice
min()
will never be called when there is no number in the stack.
思路:
因为O(1),所以用两个栈操作,stack 和 minStack。
push(int num): stack push; 如果minStack为空,minStack直接push,或者 num<=minStack的栈顶元素,minStack也push
pop(): stack pop; 如果minStack的栈顶值和stack栈顶值相等(Integer类判断两个值相等要用equals.()),minStack也pop.
min(): 返回minStack 栈顶值。
注意:
(1)push的时候,num == minStack.peek() 时,也要minStack.peek()。[line 12]
否则,有可能出现EmptyStackException:第一次pop()后,minStack为空了,再min()就会有异常。
push(1)
push(1)
push(1)
min()
pop()
min()
pop()
(2)equals 和 ==
1 public class MinStack { 2 private Stack<Integer> stack; 3 private Stack<Integer> minStack; 4 5 public MinStack() { 6 stack = new Stack<Integer>(); 7 minStack = new Stack<Integer>(); 8 } 9 10 public void push(int number) { 11 stack.push(number); 12 if (minStack.empty() || minStack.peek() >= number) { //相等时,minStack也要push 13 minStack.push(number); 14 } 15 } 16 17 public int pop() { 18 if (stack.peek().equals(minStack.peek())) //比较栈顶值,只能用equals() 19 minStack.pop(); 20 return stack.pop(); 21 } 22 23 public int min() { 24 return minStack.peek(); 25 } 26 }
原文:https://www.cnblogs.com/Jessiezyr/p/10666617.html