Created
April 9, 2018 16:30
-
-
Save shixiaoyu/6ba82dd16a323a399d4c23a5e854c599 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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