Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created April 9, 2018 16:30
Show Gist options
  • Save shixiaoyu/6ba82dd16a323a399d4c23a5e854c599 to your computer and use it in GitHub Desktop.
Save shixiaoyu/6ba82dd16a323a399d4c23a5e854c599 to your computer and use it in GitHub Desktop.
class MinStackNode {
public int val;
public int curMin;
public MinStackNode(int val, int curMin) {
this.val = val;
this.curMin = curMin;
}
}
/** Below solution is simply define a node keeps track of current minimum, saves space! **/
private Stack<MinStackNode> minStackWithNode = new Stack<>();
public void push(int x) {
if (minStackWithNode.isEmpty()) {
minStackWithNode.push(new MinStackNode(x, x));
return;
}
if (x <= minStackWithNode.peek().curMin) {
minStackWithNode.push(new MinStackNode(x, x));
} else {
minStackWithNode.push(new MinStackNode(x, minStackWithNode.peek().curMin));
}
}
public void pop() {
if (minStackWithNode.isEmpty()) {
return;
}
minStackWithNode.pop();
}
public int top(){
if (minStackWithNode.isEmpty()) {
return -1;
}
return minStackWithNode.peek().val;
}
public int getMin() {
if (minStackWithNode.isEmpty()) {
return -1;
}
return minStackWithNode.peek().curMin;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment