Problem
Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
Example
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1
Note
min operation will never be called if there is no number in the stack.
注意在push()里的条件,minstack.peek() >= number,保证最小值在minstack中。
第二点:
if (!stack.isEmpty()) {
int element = stack.peek();
if (minstack.peek() == element) {
minstack.pop();
}
}
.parseInt()
,用.equals()
都不对。.intValue()
,用==
都是对的。
if (minstack.peek().intValue() == stack.peek().intValue()) 正确
valueOf(String)
returns a new java.lang.Integer
, which is the object representative of the integer,
whereas parseInt(String)
returns a primitive integer type int
.intValue
is an instance method whereby parseInt
is a static method.
Moreover, Integer.parseInt(s)
can take primitive datatype as well.
Solution
public class MinStack {
Stack<Integer> stack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
stack.push(x);
if (minStack.isEmpty() || minStack.peek() >= x) minStack.push(x);
}
public void pop() {
if (minStack.peek().equals(stack.peek())) minStack.pop();
stack.pop();
}
//Better check if it is empty
public int top() {
return stack.peek();
}
//Better check if it is empty
public int getMin() {
return minStack.peek();
}
}
MAX STACK
public void push(int x) {
if (maxStack.isEmpty() || maxStack.peek() <= x) maxStack.push(x);
stack.push(x);
}
public int pop() {
if (maxStack.peek().equals(stack.peek())) maxStack.pop();
return stack.pop();
}
public int max() {
return maxStack.peek();
}