Skip to content

Instantly share code, notes, and snippets.

@fever324
Created November 10, 2014 19:16
Show Gist options
  • Save fever324/da778365bef2777781f5 to your computer and use it in GitHub Desktop.
Save fever324/da778365bef2777781f5 to your computer and use it in GitHub Desktop.
MinStack1
import java.util.Stack;
/*
* 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.
*/
/**
* Space - O(2n)
* push(x) - O(1)
* pop() - O(1)
* top() - O(1)
* getMin() - O(1)
* @author hongfeili
*
*/
public class MinStack {
private Stack<Integer> s;
private Stack<Integer> min;
public MinStack() {
s = new Stack();
min = new Stack();
}
public void push(int x) {
s.push(x);
if (min.size() != 0) {
min.push(min.peek() < x ? min.peek() : x);
} else {
min.push(x);
}
}
public void pop() {
min.pop();
s.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return min.peek();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment