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.
My code:
class MinStack {
private Stack<Integer> s = new Stack<>();
private Stack<Integer> min = new Stack<>();
public void push(int x){
if (min.isEmpty()){
min.push(x);
}
else{
min.push(Math.min(x,min.peek()));
}
s.push(x);
}
public void pop(){
s.pop();
min.pop();
}
public int top(){
return s.peek();
}
public int getMin(){
return min.peek();
}
}
总结:自己用了两个栈,一个用来存放最小值,比较直接,但是不够巧妙。
class MinStack {
Stack<Integer> stack=new Stack<>();
int min=Integer.MAX_VALUE;
public void push(int x) {
if(x<=min) {stack.push(min); min=x;}
stack.push(x);
}
public void pop() {
if(stack.peek()==min){ stack.pop(); min=stack.pop(); }
else stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
总结:太聪明了,如果当前值是最小值的话,把之前的min push到栈中。class MinStack {
private Node head;
public void push(int x) {
if(head == null)
head = new Node(x, x);
else
head = new Node(x, Math.min(x, head.min), head);
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
private class Node {
int val;
int min;
Node next;
private Node(int val, int min) {
this(val, min, null);
}
private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}
总结:没有用到stack,用到了自己设计的链表。其实链表就是自己设计一个class。
不太明白的地方:
private Node(int val, int min) {
this(val, min, null);
}
private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}