-
-
Save jason51122/60751e16fd55a162bf8b to your computer and use it in GitHub Desktop.
3.2 How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
This file contains 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
import java.util.Stack; | |
@SuppressWarnings("serial") | |
public class MinStack extends Stack<Integer> { | |
private Stack<Integer> minStack; | |
public MinStack() { | |
minStack = new Stack<Integer>(); | |
} | |
public void push(int val) { | |
super.push(val); | |
if (val <= min()) { | |
minStack.push(val); | |
} | |
} | |
// Must return Integer type. | |
public Integer pop() { | |
int val = super.pop(); | |
if (val == minStack.peek()) { | |
minStack.pop(); | |
} | |
return val; | |
} | |
public int min() { | |
if (super.empty()) { | |
return Integer.MAX_VALUE; | |
} | |
else { | |
return minStack.peek(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment