Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created April 9, 2018 16:28
Show Gist options
  • Save shixiaoyu/3d8097da1b245cdfd679a0461b5f0cbe to your computer and use it in GitHub Desktop.
Save shixiaoyu/3d8097da1b245cdfd679a0461b5f0cbe to your computer and use it in GitHub Desktop.
private Stack<Integer> stack = new Stack<>();
private Stack<Integer> minStack = new Stack<>();
public void push(int x) {
stack.add(x);
if (minStack.isEmpty()) {
minStack.add(x);
} else {
// Here I am only adding the element if it is <= min, another way is always add minium
if (x <= minStack.peek()) { // need to be <=, since if the same element could be added multiple times
minStack.add(x);
}
}
}
public void pop() {
if (stack.isEmpty()) {
return;
}
int v = stack.pop();
if (v == minStack.peek()) {
minStack.pop();
}
}
public int top(){
if (stack.isEmpty()) {
return -1;
}
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment