Last active
August 29, 2015 14:03
-
-
Save JoyceeLee/9fdc6b744d63b0238b3a to your computer and use it in GitHub Desktop.
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
/*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.*/ | |
public class Solution extends Stack<Integer> { | |
Stack<Integer> minSt; | |
public Solution { | |
minSt = new Stack<Integer>(); | |
} | |
public void push(int v) { | |
if(value<=min()) { | |
minSt.push(v); | |
} | |
super.push(v); | |
} | |
public Integer pop() { | |
int v = super.pop(); | |
if(v==min()) { | |
minSt.pop(); | |
} | |
return v; | |
} | |
public int min() { | |
if(minSt.isEmpty()) { | |
return Integer.MAX_VALUE; | |
} else { | |
return minSt.peek(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment