Created
April 9, 2018 16:28
-
-
Save shixiaoyu/3d8097da1b245cdfd679a0461b5f0cbe 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
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