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中。
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
Min Stack
updated 2018-9
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 (!stack.isEmpty() && !minstack.isEmpty() && minstack.peek().equals(stack.peek())) minstack.pop();
stack.pop();
}
public int top() {
if (stack.isEmpty()) return 0;
else return stack.peek();
}
public int getMin() {
if (minstack.isEmpty()) return 0;
else return minstack.peek();
}
}
Min Stack -- without using Stack class
class MinStack {
/** initialize your data structure here. */
private Node head;
private class Node {
int val;
int min;
Node next;
private Node(int min, int val, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
public void push(int x) {
if (head == null) {
head = new Node(x, x, null);
} else {
head = new Node(Math.min(head.min, x), x, head);
}
}
public void pop() {
head = head.next;
return;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
}
/**
* 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();
*/
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();
}